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>

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;
    }
}

在 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

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;
    }
}

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);
        }
    }
}

完整代码结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── oss
│   │               ├── OSSApplication.java
│   │               ├── OSSConfig.java
│   │               ├── OSSService.java
│   │               └── OSSController.java
│   └── resources
│       └── application.yml

测试上传文件到阿里云 OSS

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

POST http://localhost:8080/uploadFile

请求参数:

file: 上传的文件。

总结

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

  • 15
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值