6

Java21 + SpringBoot3集成七牛云对象存储OSS,实现文件上传 - 程序员偏安

 7 months ago
source link: https://www.cnblogs.com/breezefaith/p/18005793
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

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

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

引入maven依赖

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

<dependencies>
  <!-- 七牛云SDK -->
  <dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>[7.13.0, 7.13.99]</version>
  </dependency>
  <!-- Lombok -->
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
    <optional>true</optional>
  </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组件实现文件上传功能。如有错误,还望批评指正。

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK