阿里云OSS云存储的实现
本地存储方式有很大缺点
- 存储在磁盘路径中,可能会被误删,不安全
- 存储小效率低
这里我使用阿里云OSS进行文件的存储
1)在阿里云官网开通对象存储OSS,创建Bucket,以公共读的方式
2)获取AccessKey密钥( accessKeyId 和 accessKeySecret)
我的项目使用的是jdk8,只导入了一个依赖坐标
<!--阿里云 oss的依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<!--消除@ConfigurationProperties(prefix = "aliyun.oss")注解下警告信息,需要添加依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
@Slf4j
@RestController
@RequestMapping("/common")
public class AliOSSController {
@Autowired
private AliOSSUtils aliOSSUtils;
@PostMapping("/upload")
public R<String> upload(@RequestParam("file")MultipartFile file){
log.info("上传的文件名为:{}",file.getOriginalFilename());
String url;
try {
url = aliOSSUtils.upload(file);
} catch (IOException e) {
throw new FileUploadException("文件上传失败");
}
log.info("文件上传成功的路径地址为:{}",url);
//直接将存储图片的url路径返回
return R.success(url);
}
}
/**
* 阿里云 OSS 工具类
*/
@Component
public class AliOSSUtils {
//获取注入AliOSSProperties 的Bean对象
@Autowired
private AliOSSProperties aliOSSProperties;
/**
* 实现上传图片到OSS
*/
public String upload(MultipartFile file) throws IOException {
String accessKeyId = aliOSSProperties.getAccessKeyId();
String accessKeySecret = aliOSSProperties.getAccessKeySecret();
String bucketName = aliOSSProperties.getBucketName();
String endPoint = aliOSSProperties.getEndPoint();
// 获取上传的文件的输入流
InputStream inputStream = file.getInputStream();
// 避免文件覆盖
String originalFilename = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//上传文件到 OSS
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, fileName, inputStream);
//文件访问路径
String url = endPoint.split("//")[0] + "//" + bucketName + "." + endPoint.split("//")[1] + "/" + fileName;
// 关闭ossClient
ossClient.shutdown();
return url;// 把上传到oss的路径返回
}
}
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss") //添加配置信息的前缀
public class AliOSSProperties {
private String endPoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
aliyun:
oss:
# 这里我使用的是杭州华东区域一
endPoint: https://oss-cn-hangzhou.aliyuncs.com
accessKeyId: yourAccessKeyId
accessKeySecret: yourAccessKeySecret
bucketName: yourBucketName
这里只需要写一个upload方法即可,对应的前端页面的upload.html
handleAvatarSuccess (response, file, fileList) {
/*this.imageUrl = `/common/download?name=${response.data}`*/
/*换为云存储后,后端响应的数据就是url,直接进行回显,不需要再从本地读取回显*/
this.imageUrl = `${response.data}`
},
参考文档:https://help.aliyun.com/zh/oss/developer-reference/simple-upload-11?spm=a2c4g.11186623.0.0.3f42df3aoraRui