我的笔记会更新至我的hexo博客,欢迎访问
BDsnake’s Blog
前言
我的博客: bdsnake.top
本篇文章介绍如何在springboot项目中配置OSS服务,用一个Service类简单实现上传文件与删除文件的操作
步骤
步骤1:创建存储桶
在阿里云OSS创建存储桶
步骤2:创建RAM授权策略
记录AccessKeyId与accessKeySecret,后面会用
步骤3:在项目中添加依赖
<!-- 阿里云oss存储api -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${oss.version}</version>
</dependency>
步骤4:编写接口与实现类
写两个方法
public interface OssService {
String upload(MultipartFile file, String path);
boolean delete(String relativePath);
}
@Service
public class OssServiceImpl implements OssService {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = "xxx";
// 阿里云账号AccessKey
String accessKeyId = "xxx";
String accessKeySecret = "xxx";
String bucketName="xxx";
@Override
public String upload(MultipartFile file, String path) {
// ossClint构建
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 文件转化为字节流上传
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,path,new ByteArrayInputStream(file.getBytes()));
oss.putObject(putObjectRequest);
} catch (IOException e) {
e.printStackTrace();
return null;
}finally {
oss.shutdown();
}
return "your link"+path;
}
public boolean delete(String relativePath){
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
oss.deleteObject(bucketName,relativePath);
}catch (Exception e){
e.printStackTrace();
return false;
}finally {
oss.shutdown();
}
return true;
}
}