当前位置:   article > 正文

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

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

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

1. 引入依赖

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

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.13.2</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2. 自定义配置

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

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

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

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. 实现 OSS 服务类

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

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

4. 编写控制器类

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

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);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

完整代码结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── oss
│   │               ├── OSSApplication.java
│   │               ├── OSSConfig.java
│   │               ├── OSSService.java
│   │               └── OSSController.java
│   └── resources
│       └── application.yml
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

测试上传文件到阿里云 OSS

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

POST http://localhost:8080/uploadFile
  • 1

请求参数:

file: 上传的文件。
  • 1

总结

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/618628
推荐阅读
相关标签
  

闽ICP备14008679号