提示:此文章主要用来记忆oss上传需要注意的地方
前言
使用oss最后上传文件时需要提供文件名,但如果上传同一名称的文件时会覆盖掉上一个文件,所以这里会使用UUID+文件名拼接达到区分效果。同时,为了整理分类,一般企业规范要求 文件路径以时间为标准如:yyyy/MM/dd 2023/03/27。所以此文主要解决以上内容。
一、OSS是什么?
是一款海量、安全、低成本、高可靠的云存储服务,提供99.9999999999%(12个9)的数据持久性,99.995%的数据可用性。多种存储类型供选择,全面优化存储成本。
二、使用步骤
1.引入库
代码如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
</dependencies>
这里引入了 hutool包用以方便等会时间格式处理
2.上传文件代码
代码如下:
注意 endpoint、accessKeyId、accessKeySecret 、accessKeySecret 换成自己对应的
public String uploadFileAvatar(MultipartFile file) {
//下面四个属性记得换成自己的
String endpoint = ConstantPropertiesUtil.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = ConstantPropertiesUtil.KEY_ID;
String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
// 填写Bucket名称,例如examplebucket。
String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
//拼接代码如下
String fileName = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
String path = LocalDateTimeUtil.format(LocalDateTimeUtil.now(),"yyyy/MM/dd");
//拼接
fileName = path + "/" + uuid + fileName;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = file.getInputStream();
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
// 设置该属性可以返回response。如果不设置,则返回的response为空。
putObjectRequest.setProcess("true");
// 创建PutObject请求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
// 如果上传成功,则返回200。
System.out.println(result.getResponse().getStatusCode());
String url = "http://"+bucketName+"."+endpoint+"/"+fileName ;
return url;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
return null;
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
return null;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
详情请参考官方文档
总结
简单记录一下~