• Spring Boot 实现文件本地以及OSS上传


    Spring Boot 实现文件上传

    Maven依赖

    <dependency>
       <groupId>com.aliyun.ossgroupId>
       <artifactId>aliyun-sdk-ossartifactId>
       <version>3.15.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    上传到本地

    package yang.controller;
    
    import java.util.UUID;
    
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestPart;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    
    @RestController
    @RequestMapping("/upload")
    public class UploadController {
        @PostMapping
        public void upload(@RequestPart MultipartFile file) throws IOException {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件扩展名
            String extName = fileName.substring(fileName.lastIndexOf("."));
            // 获取项目根目录
            String root = System.getProperty("user.dir");
            // 获取文件存放目录
            String fileDir = "/src/main/java/yang/upload/";
    
            // 如果目标目录不存在就创建
            File dir = new File(root + fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
    
            // 生成不重复的文件名称
            String uuidName = UUID.randomUUID().toString() + extName;
    
            // 文件上传的位置
            String uploadDir = root + fileDir + uuidName;
    
            // 上传文件
            file.transferTo(new File(uploadDir));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    上传到OSS

    package yang.controller;
    
    import java.util.UUID;
    
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestPart;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import yang.pojo.Result;
    
    import java.io.InputStream;
    
    @RestController
    @RequestMapping("/upload")
    public class UploadController {
        @PostMapping
        public Result upload(@RequestPart MultipartFile file) throws IOException {
            // Endpoint(地域节点)
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    
            // 秘钥
            String accessKeyId = "LTAI5tNVbvdh8BGmnK3GNa4i";
            String accessKeySecret = "JXN5Mc3e40QlOxGBBUVJjAsw2TNCR2";
    
            // Bucket名称
            String bucketName = "qweqweqweqweqw12312cds";
    
            // 文件名称
            String fileName = file.getOriginalFilename();
            // 创建一个不重复的文件名称
            String uuidName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // 文件输入流
                InputStream inputStream = file.getInputStream();
    
                // 将文件上传到OSS
                ossClient.putObject(bucketName, uuidName, inputStream);
    
                // 文件访问路径
                String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + uuidName;
    
                return Result.success(url);
            } catch (OSSException oe) {
                System.out.println("捕获了 OSSException, 这意味着您的请求已发送到 OSS, 但由于某种原因被拒绝并显示错误响应");
                return Result.error(oe.getMessage());
            } catch (ClientException ce) {
                System.out.println("捕获 ClientException, 表示客户端在尝试与 OSS 通信时遇到, 严重的内部问题, 例如无法访问网络。");
                return Result.error(ce.getMessage());
            } finally {
                if (ossClient != null) {
                    // 最后记得关闭ossClient
                    ossClient.shutdown();
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    封装工具类

    上面的代码我们可以定义一个工具类,这样在任何需要文件上传的地方只需要调用 upload 方法即可,大大减少了代码量

    package yang.utils;
    
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.UUID;
    
    @Component
    public class AliOSSUtils {
        private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        private String accessKeyId = "LTAI5tNVbvdh8BGmnK3GNa4i";
        private String accessKeySecret = "JXN5Mc3e40QlOxGBBUVJjAsw2TNCR2";
        private String bucketName = "qweqweqweqweqw12312cds";
    
        public String upload(MultipartFile file) throws IOException {
            InputStream inputStream = file.getInputStream();
    
            String fileName = file.getOriginalFilename();
            String uuidName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
    
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, uuidName, inputStream);
    
            String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + uuidName;
    
            ossClient.shutdown();
    
            return url;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    使用工具类

    @PostMapping
    public Result upload(@RequestPart MultipartFile file) throws IOException {
        AliOSSUtils oss = new AliOSSUtils();
        String url = oss.upload(file);
    
        return Result.success(url);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    Centos在NAT模式下的设置
    开发ABAP程序中的错误
    前端 html 中的 meta 标签有哪些用处?
    【MySQL —— 索引】
    基于图搜索的规划算法之 A* 家族(八):Theta* 算法
    4个技巧告诉你,如何使用SMS促进业务销售?
    模型层及ORM介绍
    Conda包依赖侦探:conda inspect命令全解析
    阿里云-系统盘-磁盘扩容
    不同写法的性能差异
  • 原文地址:https://blog.csdn.net/haodian666/article/details/136523135