Spring Boot :将文件推送到阿里云 OSS

阿里云对象存储服务(OSS)是一个海量、安全、低成本、高可靠的云存储服务。本文将介绍如何在 Spring Boot 项目中将文件推送到阿里云 OSS,包括引入依赖、自定义配置、实现上传文件的方法和编写控制器来处理上传文件。

1. 引入依赖

首先,在 Spring Boot 项目的 pom.xml 文件中引入阿里云 OSS SDK 的依赖:

bash 复制代码
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.13.2</version>
</dependency>

2. 自定义配置

创建一个配置类 OSSConfig,用于配置 OSS 连接的相关参数:

bash 复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
public class OSSConfig {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    // Getters and Setters
    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
}

在 application.yml 文件中添加阿里云 OSS 的相关配置:

bash 复制代码
aliyun:
  oss:
    endpoint: your-oss-endpoint
    access-key-id: your-access-key-id
    access-key-secret: your-access-key-secret
    bucket-name: your-bucket-name

3. 实现 OSS 服务类

创建一个服务类 OSSService,用于连接 OSS 并上传文件:

bash 复制代码
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class OSSService {

    @Autowired
    private OSSConfig ossConfig;

    public String uploadFile(MultipartFile file) {
        String fileUrl = "";
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

        try {
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream);
            fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
        } catch (OSSException | IOException e) {
            throw new RuntimeException("上传文件到 OSS 失败", e);
        } finally {
            ossClient.shutdown();
        }

        return fileUrl;
    }
}

4. 编写控制器类

创建一个控制器类 OSSController,用于处理文件上传请求并调用 OSSService 进行文件上传:

bash 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class OSSController {

    @Autowired
    private OSSService ossService;

    @PostMapping("/uploadFile")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = ossService.uploadFile(file);
            return new ResponseEntity<>(fileUrl, HttpStatus.OK);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

完整代码结构

bash 复制代码
src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── oss
│   │               ├── OSSApplication.java
│   │               ├── OSSConfig.java
│   │               ├── OSSService.java
│   │               └── OSSController.java
│   └── resources
│       └── application.yml

测试上传文件到阿里云 OSS

启动 Spring Boot 应用程序,使用 Postman 或类似工具发送 POST 请求至以下 URL,并上传要推送到 OSS 的文件:

bash 复制代码
POST http://localhost:8080/uploadFile

请求参数:

复制代码
file: 上传的文件。

总结

通过本文,我们成功地在 Spring Boot 项目中实现了将文件推送到阿里云 OSS 的功能。我们通过引入阿里云 OSS SDK 依赖、自定义 OSS 配置、创建 OSS 服务类和控制器类,实现了文件的上传和管理。这种方式可以帮助我们在各种应用场景中将文件高效地推送到阿里云 OSS,方便文件的存储和共享。

相关推荐
PetterHillWater16 分钟前
Trae中实现OOP原则工程重构
后端·aigc
圆滚滚肉肉20 分钟前
后端MVC(控制器与动作方法的关系)
后端·c#·asp.net·mvc
SimonKing20 分钟前
拯救大文件上传:一文彻底彻底搞懂秒传、断点续传以及分片上传
java·后端·架构
深栈解码20 分钟前
JUC并发编程 内存布局和对象头
java·后端
37手游后端团队22 分钟前
巧妙利用装饰器模式给WebSocket连接新增持久化
后端
编程乐趣25 分钟前
C#版本LINQ增强开源库
后端
tonydf26 分钟前
记一次近6万多个文件的备份过程
windows·后端
前端付豪26 分钟前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
加瓦点灯27 分钟前
Spring AI + Milvus 实现 RAG 智能问答系统实战
后端
JohnYan28 分钟前
Bun技术评估 - 07 S3
javascript·后端·bun