springboot 阿里云oss
时间: 2023-11-09 22:00:32 浏览: 114
阿里云提供了Java SDK,通过该SDK,我们可以方便地在springboot中集成阿里云oss服务,实现文件的上传、下载、删除等操作。具体步骤如下:
1. 引入阿里云oss SDK依赖
```xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.6.1</version>
</dependency>
```
2. 在application.properties中配置oss相关参数
```properties
# oss访问地址
aliyun.oss.endpoint=yourEndpoint
# oss访问的accessKeyId
aliyun.oss.accessKeyId=yourAccessKeyId
# oss访问的accessKeySecret
aliyun.oss.accessKeySecret=yourAccessKeySecret
# oss的bucket名称
aliyun.oss.bucketName=yourBucketName
```
3. 编写oss工具类,实现文件的上传、下载、删除等操作
```java
@Service
public class OSSUtil {
@Autowired
private OSSClient ossClient;
// 上传文件
public void uploadFile(String key, InputStream inputStream) {
ossClient.putObject(bucketName, key, inputStream);
}
// 下载文件
public void downloadFile(String key, OutputStream outputStream) {
OSSObject ossObject = ossClient.getObject(bucketName, key);
InputStream inputStream = ossObject.getObjectContent();
try {
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 删除文件
public void deleteFile(String key) {
ossClient.deleteObject(bucketName, key);
}
}
```
阅读全文