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>
  <!-- 七牛云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.png

总结

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

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

  • 23
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现Spring Boot整合七牛云上传文件,可以按照以下步骤进行: 1.引入七牛云Java SDK 在pom.xml中引入七牛云Java SDK: ```xml <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.2.0,)</version> </dependency> ``` 2.配置七牛云参数 在application.yml或application.properties中添加七牛云的参数: ```yml qiniu: accessKey: your_access_key secretKey: your_secret_key bucket: your_bucket_name domain: your_domain_name ``` 3.编写上传文件的代码 在需要上传文件的地方编写上传文件的代码,示例代码如下: ```java @Service public class QiniuService { @Autowired private QiniuConfig qiniuConfig; /** * 上传文件到七牛云 * * @param file 文件对象 * @return 文件访问URL */ public String uploadFile(File file) throws QiniuException { // 构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.autoZone()); // ...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); // 生成上传凭证,然后准备上传 String accessKey = qiniuConfig.getAccessKey(); String secretKey = qiniuConfig.getSecretKey(); String bucket = qiniuConfig.getBucket(); // 如果是Windows情况下,格式是 D:\\qiniu\\test.png String localFilePath = file.getAbsolutePath(); // 默认不指定key的情况下,以文件内容的hash值作为文件名 String key = null; Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(localFilePath, key, upToken); // 解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); return qiniuConfig.getDomain() + "/" + putRet.key; } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { // ignore } throw ex; } } } ``` 4.测试上传文件 在测试类中编写测试上传文件的代码,示例代码如下: ```java @RunWith(SpringRunner.class) @SpringBootTest public class QiniuServiceTest { @Autowired private QiniuService qiniuService; @Test public void testUploadFile() throws QiniuException { File file = new File("test.png"); String url = qiniuService.uploadFile(file); System.out.println(url); } } ``` 其中,test.png是要上传的文件名。运行测试类即可上传文件到七牛云,并返回文件的访问URL。 以上就是Spring Boot整合七牛云上传文件的全部步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

偏安zzcoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值