亲宝软件园·资讯

展开

springboot+thymeleaf对象存储图片

程序员小徐同学 人气:0

今天再进行创建项目时想使用阿里云oos进行存储图片 下面进行实操

1.先引入pom依赖

  <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.9.1</version>
        </dependency>

2.编写前端thymleeaf代码tetsfile.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>

</style>

<body>

<img  th:src="${url}" alt="" width="300px">

<form action="fileUpload" method="post" enctype="multipart/form-data">
    <input type="file" name="fileName">
    <input type="submit">
</form>
</body>
</html>

3.service层编写

下面的代码需要4个参数

package com.xuda.ntf.service;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-05-07 10:33
 */
@Service
@Slf4j
public class AliyunOSSUtilService {

    /**
     * 这五个分别是什么下面会说
     * aliyun.oss.endpoint=oss-cn-shanghai.aliyuncs.com
     * aliyun.oss.accessKeyId=L相关密钥
     * aliyun.oss.secret=eF0相关密钥
     * aliyun.oss.bucket=yygh-xuda
     */
    public static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
    public static final String accessKeyId = "LTA个人密钥";
    public static final String accessKeySecret = "eF0UmiWp2回传密钥";
    public static final String bucketName = "yygh-xuda回传name";
    public static final String fileHost = "2022/cff"; //图片头部

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 上传
     *
     * @param file
     * @return
     */
    public String upload(File file) {
        log.info("=========>OSS文件上传开始:" + file.getName());
//        String fileHost=constantProperties.getFilehost();
        System.out.println(endpoint + "endpoint");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if (null == file) {
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            //容器不存在,就创建
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (null != result) {
                log.info("==========>OSS文件上传成功,OSS地址:" + fileUrl);
                return fileUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        } finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * @desc 查看文件列表
     */
    public List<OSSObjectSummary> getObjectList() {
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
        listObjectsRequest.setPrefix(fileHost + "/");
        ObjectListing objectListing = ossClient.listObjects(listObjectsRequest.withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    /**
     * 获取文件临时url
     *
     * @param objectName    oss中的文件名
     * @param
     */
    public String getUrl(String objectName ,long effectiveTime) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间
        Date expiration = new Date(new Date().getTime() + effectiveTime);
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, objectName);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }


    /**
     * 删除OSS中的单个文件
     *
     * @param objectName 唯一objectName(在oss中的文件名字)
     */
    public void delete(String objectName) {
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 删除文件。
            ossClient.deleteObject(bucketName, objectName);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.controller层编写

写到代码中取

package com.xuda.ntf.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import com.xuda.ntf.service.AliyunOSSUtilService;
import com.xuda.ntf.service.FileService;
import com.xuda.ntf.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-05-07 9:39
 */
@Slf4j
@Controller
public class FileApiController {

    String uploadUrl = "";
    @Autowired
    private AliyunOSSUtilService aliyunOSSUtil;

    /**
     * 查看图片
     *
     */
    @RequestMapping("/getAllPic")
    public String getAllPic(Model model){
//        Hashtable hashtable = new Hashtable();
        // 显示图片
        ArrayList<String> listStr = new ArrayList<>();
        List<OSSObjectSummary> list = aliyunOSSUtil.getObjectList();
        String url = aliyunOSSUtil.getUrl(uploadUrl,5000);
       /* list.forEach(item -> {
//                    这个将自己上传图片得地址复制到这里来
                    listStr.add("https://yygh-xuda.oss-cn-shanghai.aliyuncs.com/"+item.getKey());

                }
        );*/
        model.addAttribute("fileNames",listStr);
        model.addAttribute("url",url);
        return "testfile.html";
    }

    /**
     *
     * @param file 要上传的文件
     * @return
     */
    @RequestMapping("/fileUpload")
    public String upload(@RequestParam("fileName") MultipartFile file,Model model){
        try {
            if(null != file){
                String filename = file.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = aliyunOSSUtil.upload(newFile);
                    System.out.println(uploadUrl);
                    model.addAttribute("file",uploadUrl);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return "forward:getAllPic";
    }

}

 到此这篇关于springboot+thymeleaf整合阿里云OOS对象存储图片的实现的文章就介绍到这了,更多相关springboot+thymeleaf对象存储图片内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

加载全部内容

相关教程
猜你喜欢
用户评论