SpringBoot + oss 实现文件上传
时间: 2023-05-31 09:06:35 浏览: 140
SpringBoot可以通过阿里云的OSS(Object Storage Service)实现文件上传,以下是实现步骤:
1. 引入阿里云OSS SDK依赖
在pom.xml中引入以下依赖:
```xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
```
2. 配置OSS连接信息
在application.properties文件中配置OSS连接信息:
```properties
oss.endpoint=your-endpoint
oss.accessKeyId=your-access-key-id
oss.accessKeySecret=your-access-key-secret
oss.bucketName=your-bucket-name
```
3. 创建OSS客户端
在配置类中创建OSS客户端:
```java
@Configuration
public class OSSConfiguration {
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@Bean
public OSSClient ossClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
}
```
4. 实现上传接口
```java
@RestController
public class UploadController {
@Autowired
private OSSClient ossClient;
@Value("${oss.bucketName}")
private String bucketName;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
try {
ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()));
return "success";
} catch (IOException e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
}
return "fail";
}
}
```
以上就是通过阿里云OSS实现文件上传的步骤。
阅读全文