• Java21 + SpringBoot3集成七牛云对象存储OSS,实现文件上传


    前言

    近日心血来潮想做一个开源项目,目标是做一款可以适配多端、功能完备的模板工程,包含后台管理系统和前台系统,开发者基于此项目进行裁剪和扩展来完成自己的功能开发。本项目为前后端分离开发,后端基于Java21SpringBoot3开发,后端使用Spring SecurityJWTSpring Data JPA等技术栈,前端提供了vueangularreactuniapp微信小程序等多种脚手架工程。

    项目地址:https://gitee.com/breezefaith/fast-alden

    项目中使用七牛云对象存储Kodo作为云端文件存储中心,本文主要介绍如何在SpringBoot中集成七牛云OSS,并结合前端使用Element Plus库的Upload组件实现文件上传功能。

    实现步骤

    引入maven依赖

    在pom.xml中引入七牛云及其相关依赖,本文还引入了lombok用于简化代码。

    <dependencies>
      
      <dependency>
        <groupId>com.qiniugroupId>
        <artifactId>qiniu-java-sdkartifactId>
        <version>[7.13.0, 7.13.99]version>
      dependency>
      
      <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.30version>
        <optional>trueoptional>
      dependency>
    dependencies>
    

    修改配置文件

    application.yml中可以自定义七牛云相关配置信息。

    fast-alden:
      file:
        oss:
          qiniu:
            access-key: *** # 请从七牛云工作台-个人中心-密钥管理获取
            secret-key: *** # 请从七牛云工作台-个人中心-密钥管理获取
            bucket: demo # 七牛云存储空间名称
            directory: upload/ # 自定义存储空间内目录
            domain: https://qiniu.demo.com/ # 存储空间自定义域名,请提前在存储空间中进行配置
    

    创建七牛云配置类

    /**
     * 七牛云OSS相关配置
     */
    @Configuration
    @ConfigurationProperties(prefix = "fast-alden.file.oss.qiniu")
    @Getter
    @Setter
    public class QiniuConfig {
        /**
         * AC
         */
        private String accessKey;
        /**
         * SC
         */
        private String secretKey;
        /**
         * 存储空间
         */
        private String bucket;
        /**
         * 上传目录
         */
        private String directory;
        /**
         * 访问域名
         */
        private String domain;
    }
    
    

    创建文件操作服务类

    创建文件操作服务类接口。

    /**
     * 文件操作服务
     */
    public interface FileService {
        /**
         * 文件上传
         *
         * @param file 待上传的文件
         * @return 访问该文件的url
         * @throws IOException
         */
        String upload(MultipartFile file) throws IOException;
    }
    
    

    创建文件操作服务实现类,基于七牛云SDK实现。

    /**
     * 七牛云对象存储文件服务
     */
    @Service("fileService")
    public class QiniuFileServiceImpl implements FileService {
        private final QiniuConfig qiniuConfig;
    
        public QiniuFileServiceImpl(QiniuConfig qiniuConfig) {
            this.qiniuConfig = qiniuConfig;
        }
    
        @Override
        public String upload(MultipartFile file) throws IOException {
            if (file.isEmpty()) {
                throw new RuntimeException("文件是空的");
            }
            // 创建上传token
            Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
    
            // 设置上传配置,Region要与存储空间所属的存储区域保持一致
            Configuration cfg = new Configuration(Region.huadongZheJiang2());
    
            // 创建上传管理器
            UploadManager uploadManager = new UploadManager(cfg);
    
            String originalFilename = file.getOriginalFilename();
            // 构造文件目录和文件名
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileKey = qiniuConfig.getDirectory() + UUID.randomUUID() + suffix;
    
            // 上传文件
            Response response = uploadManager.put(file.getInputStream(), fileKey, upToken, null, null);
    
            // 返回文件url
            return qiniuConfig.getDomain() + fileKey;
        }
    }
    
    

    上述代码中有一行用到了Region.huadongZheJiang2(),此处要与自己的存储空间所属的存储区域保持一致,本文中所使用的存储空间属于华东-浙江2区域。

    创建文件操作控制器

    @RestController
    @RequestMapping("/file")
    public class FileController {
        private final FileService fileService;
    
        public FileController(FileService fileService) {
            this.fileService = fileService;
        }
    
        @PostMapping("/upload")
        public String upload(MultipartFile multipartFile) throws IOException {
            return fileService.upload(multipartFile);
        }
    }
    
    

    前端实现

    本工程前端基于Vue3组合式API开发,使用Element Plus作为UI库,借助Upload组件实现文件上传,本文在使用Upload组件时并没有直接使用其action属性,而是通过http-requeston-success属性实现了自定义的文件上传过程。

    <script setup>
      import axios from "axios";
      import { ElButton, ElMessage } from "element-plus";
    
      const uploadFile = async (options) => {
        const formData = new FormData();
        formData.append("file", options.file);
        return axios.post(`/file/upload`, formData);
      };
    
      const onUploadFileSuccess = async () => {
        ElMessage({
          message: "上传成功", type: "success"
        });
      }
    script>
    
    <template>
      <ElForm>
        <ElFormItem>
          <ElUpload action="" :http-request="uploadFile" :on-success="onUploadFileSuccess">
            <ElButton type="primary">点击上传文件ElButton>
          ElUpload>
        ElFormItem>
      ElForm>
    template>
    

    运行效果

    image

    总结

    本文主要介绍如何在SpringBoot中集成七牛云OSS,并结合前端使用Element Plus库的Upload组件实现文件上传功能。如有错误,还望批评指正。

    在后续实践中我也是及时更新自己的学习心得和经验总结,希望与诸位看官一起进步。

  • 相关阅读:
    PAT甲级考试知识点总结和一些看法
    10. Spring源码篇之BeanPostProcessor
    最新Prompt预设词分享,DALL-E3文生图+文档分析
    算法:O(1) 时间插入、删除和获取随机元素---哈希表+动态数组
    Fiddler抓包原理及其配置
    MQ基础介绍
    家政管理系统设计与实现
    力扣(LeetCode)123. 买卖股票的最佳时机 III(C++)
    JDBC批量插入数据
    Abbkine活细胞溶酶体染色试剂盒:高特异性,荧光稳定性强
  • 原文地址:https://www.cnblogs.com/breezefaith/p/18005793