05-springboot中使用阿里云oss
在Spring Boot中使用阿里云OSS上传文件,你需要做以下几个步骤:
- 引入阿里云OSS依赖
- 配置阿里云OSS的参数
- 创建OSSClient实例
- 使用OSSClient上传文件
以下是一个简单的例子:
- 在
pom.xml
中添加阿里云OSS依赖:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
- 在
application.properties
或application.yml
中配置阿里云OSS参数:
# 阿里云OSS参数配置
aliyun.oss.endpoint=你的EndPoint
aliyun.oss.accessKeyId=你的AccessKeyId
aliyun.oss.accessKeySecret=你的AccessKeySecret
aliyun.oss.bucketName=你的BucketName
- 创建配置类,用于读取配置并创建OSSClient实例:
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OssConfig {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Bean
public OSS ossClient() {
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
- 创建Service或Controller用于上传文件:
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
public class FileUploadController {
@Autowired
private OSS ossClient;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@PostMapping("/upload")
public String upload(MultipartFile file) {
String fileName = file.getOriginalFilename();
// 日期目录
String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 文件完整路径
String filePath = "file/" + datePath + "/" + fileName;
// 上传文件
ossClient.putObject(bucketName, filePath, file.getInputStream());
评论已关闭