SpringBoot + oss 实现文件上传

SpringBoot是一个基于Spring框架的快速开发脚手架,它极大简化了使用Spring框架的难度。而阿里云OSS是阿里云提供的分布式对象存储服务,具有高可用、高可靠和强安全性等特点。下面是使用SpringBoot + oss 实现文件上传的几个步骤:

1. 引入云存储SDK依赖

<dependency>
    <groupId>com.aliyun.ossgroupId>
    <artifactId>aliyun-sdk-ossartifactId>
    <version>2.9.3version>
dependency>

2. 配置OSS参数

application.properties 中添加以下配置:

oss.endpoint=oss-cn-hangzhou.aliyuncs.com
oss.accessKeyId=your_accessKeyId
oss.accessKeySecret=your_accessKeySecret
oss.bucketName=your_bucketName
oss.folder=your_folder

3. 创建OSS客户端

@Configuration
public class OSSClientConfig {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.folder}")
    private String folder;

    @Bean
    public OSSClient ossClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    @Bean
    public String bucketName() {
        return bucketName;
    }

    @Bean
    public String folder() {
        return folder;
    }
}

4. 编写文件上传服务

@Service
public class FileUploadService {

    private final OSSClient ossClient;
    private final String bucketName;
    private final String folder;

    public FileUploadService(OSSClient ossClient, String bucketName, String folder) {
        this.ossClient = ossClient;
        this.bucketName = bucketName;
        this.folder = folder;
    }

    public String uploadFile(String fileName, InputStream inputStream) throws IOException {
        // 设置文件路径
        String key = folder + "/" + fileName;
        // 上传文件
        ossClient.putObject(bucketName, key, inputStream);
        // 关闭OSSClient
        ossClient.shutdown();
        // 返回文件链接
        return "https://" + bucketName + "." + ossClient.getEndpoint().toString() + "/" + key;
    }
}

5. 在Controller中使用文件上传服务

@RestController
public class FileUploadController {

    private final FileUploadService fileUploadService;

    public FileUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        return fileUploadService.uploadFile(file.getOriginalFilename(), file.getInputStream());
    }
}

以上就是使用SpringBoot + oss 实现文件上传的步骤,通过以上的步骤可以方便快捷地实现文件上传功能。

你可能感兴趣的:(spring,boot,后端,java)