如何在 Spring Boot 项目中集成七牛云存储
在本教程中,我们将展示如何在 Spring Boot 项目中集成七牛云存储服务,实现文件上传、列举文件和删除文件等基本功能。七牛云提供强大的文件存储和管理功能,我们可以通过其 Java SDK 来方便地操作云端文件。
前置准备
1. 注册七牛云账户
首先,你需要注册并登录 七牛云官网,创建一个存储空间,并获得 Access Key 和 Secret Key。这些密钥将在接下来的代码中用于认证。
2. 创建存储空间(Bucket)
在七牛云控制台中创建一个存储空间(Bucket),并记下空间名称,这将在后续的代码中使用。
3. 配置 Maven 依赖
你需要在项目中添加七牛云 SDK 的 Maven依赖。
Maven 依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
4.配置文件application.yml
spring:
thymeleaf:
prefix: classpath:/templates/
check-template-location: true
suffix: .html
encoding: UTF-8
servlet:
content-type: text/html
mode: HTML5
cache: false
servlet:
multipart:
enabled: true
max-file-size: 30MB
max-request-size: 30MB
项目结构
本项目包含以下三个主要类:
- QiniuClient:用于与七牛云进行交互的客户端,提供文件上传、删除和列举功能。
- QiniuController:控制器层,负责处理用户请求,包括文件上传、文件列表展示和文件删除。
- QiniuConstant:存储七牛云的
Access Key
、Secret Key
和Bucket Name
等常量信息。
1. 创建 QiniuClient 类
QiniuClient
类封装了与七牛云的交互。它提供了获取上传 Token、上传文件、列出文件、删除文件等方法。