springboot整合oss
时间: 2023-10-01 11:08:20 浏览: 89
springboot整合oss实现文件的上传,查看,删除,下载
好的,下面是将Spring Boot与阿里云OSS整合的步骤:
1. 在阿里云OSS上创建一个Bucket,并获取Access Key ID和Access Key Secret
2. 在pom.xml中添加依赖:
```
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.0</version>
</dependency>
```
3. 创建一个OSS配置类,用于连接阿里云OSS:
```java
@Configuration
public class OSSConfig {
private String endpoint = "oss-cn-hangzhou.aliyuncs.com";
private String accessKeyId = "your_access_key_id";
private String accessKeySecret = "your_access_key_secret";
@Bean
public OSSClient ossClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
}
```
4. 创建一个OSS服务类,用于上传文件到阿里云OSS:
```java
@Service
public class OSSService {
@Autowired
private OSSClient ossClient;
public String upload(String bucketName, String key, InputStream inputStream) {
PutObjectResult result = ossClient.putObject(bucketName, key, inputStream);
return result.getETag();
}
}
```
5. 在Controller中调用OSS服务类上传文件:
```java
@RestController
public class OSSController {
@Autowired
private OSSService ossService;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
String bucketName = "your_bucket_name";
String key = file.getOriginalFilename();
return ossService.upload(bucketName, key, inputStream);
}
}
```
通过以上步骤,就可以在Spring Boot中实现与阿里云OSS的整合了。
阅读全文