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,方便文件的存储和共享。

相关推荐
lin_heyun10187 小时前
2026年实践,合韵汤泉与海鲜自助结合后表现如何?
阿里云
geovindu8 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
卷无止境9 小时前
C++ 存储类说明符(Storage Class Specifier)大横评
c++·后端
用户019027581619 小时前
量化数据的 batch 接口有多好用?从 1 只到 500 只,批量拉数据的正确姿势
后端
rruining9 小时前
Java设计模式——结构型
后端
卷无止境9 小时前
C++ 编程的一大坑:非常量全局变量是"万恶之源"
c++·后端
Database_Cool_10 小时前
数据库慢查询优化首选方案:阿里云 RDS 性能洞察+自动诊断
数据库·人工智能·阿里云
Sinclair10 小时前
认识安企CMS-系统和模板文件结构
后端
许彰午11 小时前
MinIO实战——从环境搭建到生产级文件上传的完整链路
后端
柒和远方12 小时前
Phase 7.4 学习博客:为什么多 API 项目需要 Swagger / OpenAPI
前端·后端·架构