​​​​​一.在Spring的yml文件配置OSS信息

aliyun:
  oss:
    endpoint:****************  # oss对外服务的访问域名
    accessKeyId::****************  # 访问身份验证中用到用户标识
    accessKeySecret: :**************** # 用户用于加密签名字符串和oss用来验证签名字符串的**
    bucketName: :**************** # oss的存储空间
    urlPrefix: :**************** #用户上传文件时指定的前缀
    policy:
      expire: 300 # 签名有效期(S)
    maxSize: 2048 # 上传文件大小(M)
    #callback: # 文件上传成功后的回调地址

 

#设置SpringBoot内嵌的TomCat默认上传大小配置 
spring:
  #设置SpringBoot内嵌的TomCat默认上传大小配置
  servlet:
    multipart:
      max-file-size: 2048MB
      max-request-size: 4096MB

 二.创建AliyunConfig实体类

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author DengCe
 * @date 2020/9/15 10:08
 * @description 文件上传
 */
@Data
@Configuration
public class AliyunConfig {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    @Bean
    public OSS oSSClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

}

 三.创建返回的结果实体

 

package com.newclass.oss;

import lombok.Data;

/**
 * @author DengCe
 * @date 2020/9/15 10:07
 * @description
 */
@Data
public class OssUploadResult {
    // 文件唯一标识
    private String uid;
    // 文件名
    private String name;
    // 状态有:uploading done error removed
    private String status;
    // 服务端响应内容,如:'{"status": "success"}'
    private String response;
}

 四.创建控制器层

package com.newclass.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import com.newclass.oss.OssUploadResult;
import com.newclass.service.OssUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author DengCe
 * @desc
 * @date 2020/9/15 10:53
 */
@Controller
@RequestMapping({"/oss/"})
public class OssUploadController {
    @Autowired
    private OssUploadService ossUploadService;

    /**
     * @return FileUploadResult
     * @author DengCe
     * @desc 文件上传到oss
     * @Param uploadFile
     */
    @RequestMapping("upload")
    @ResponseBody
    public OssUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
            throws Exception {
        return this.ossUploadService.upload(uploadFile);
    }

    /**
     * @return FileUploadResult
     * @desc 根据文件名删除oss上的文件
     * @author DengCe
     * @Param objectName
     */
    @RequestMapping("delete")
    @ResponseBody
    public OssUploadResult delete(@RequestParam("fileName") String objectName)
            throws Exception {
        return this.ossUploadService.delete(objectName);
    }

    /**
     * @return List<OSSObjectSummary>
     * @author DengCe
     * @desc 查询oss上的所有文件
     * @Param
     */
    @RequestMapping("list")
    @ResponseBody
    public List<OSSObjectSummary> list()
            throws Exception {
        return this.ossUploadService.list();
    }

    /**
     * @return
     * @author DengCe
     * @desc 根据文件名下载oss上的文件
     * @Param objectName
     */
    @RequestMapping("download")
    @ResponseBody
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        this.ossUploadService.exportOssFile(response.getOutputStream(), objectName);
    }


}

五.创建Service实现

package com.newclass.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.newclass.oss.AliyunConfig;
import com.newclass.oss.OssUploadResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.List;

/**
 * @author DengCe
 * @date 2020/9/15 10:08
 * @description 文件上传
 */
@Service
public class OssUploadService {

    @Autowired
    private OSS ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;

    /**
     * @author DengCe
     * @desc 文件上传
     */
    public OssUploadResult upload(MultipartFile uploadFile) {
        //封装Result对象,并且将文件的byte数组放置到result对象中
        OssUploadResult ossUploadResult = new OssUploadResult();
        //文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            ossUploadResult.setStatus("error");
            return ossUploadResult;
        }
        ossUploadResult.setStatus("done");
        ossUploadResult.setResponse("success");
        ossUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        ossUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return ossUploadResult;
    }

    /**
     * @author DengCe
     * @desc 生成路径以及文件名 例如:newclass/2020/9/16/1600226743123965866.jpg
     * 可以将yml文件中的OSS配置urlPrefix属性设置为OSS服务器访问前缀,这样封装的返回信息中,可以返回上传的路径
     */
    private String getFilePath(String sourceFileName) {
        LocalDate localDate = LocalDate.now();
        return "newclass/" + localDate.getYear()
                + "/" + localDate.get(ChronoField.MONTH_OF_YEAR) + "/"
                + localDate.getDayOfMonth() + "/" + System.currentTimeMillis() +
//                RandomUtils.nextInt(100, 9999)
                (int)((Math.random()*9+1)*100000)
                + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    /**
     * @author DengCe
     * @desc 查看文件列表
     */
    public List<OSSObjectSummary> list() {
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    /**
     * @author DengCe
     * @desc 删除文件
     */
    public OssUploadResult delete(String objectName) {
        // 根据BucketName,objectName删除文件
        ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
        OssUploadResult ossUploadResult = new OssUploadResult();
        ossUploadResult.setName(objectName);
        ossUploadResult.setStatus("removed");
        ossUploadResult.setResponse("success");
        return ossUploadResult;
    }

    /**
     * @author DengCe
     * @desc 下载文件
     */
    public void exportOssFile(OutputStream os, String objectName) throws IOException {
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        // 读取文件的详细内容。
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) != -1) {
            out.write(buffer, 0, lenght);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }

}

 六.postman测试接口

SpringBoot使用OSS上传文件复制粘贴篇

相关文章:

  • 2022-12-23
  • 2021-07-22
  • 2021-11-18
  • 2021-06-21
  • 2022-12-23
  • 2021-12-04
  • 2021-12-07
  • 2022-12-23
猜你喜欢
  • 2021-12-18
  • 2021-04-02
  • 2021-09-01
  • 2021-12-30
  • 2022-12-23
  • 2021-07-30
  • 2021-09-29
相关资源
相似解决方案