阿里云对象存储OSS实现文件上传
=oss==是对象存储服务(Object Storage Service)的缩写,是一种分布式存储服务,用于存储和访问大规模数据。它提供了可靠、安全、低成本的数据存储解决方案,可以通过网络随时随地访问存储的数据。oss常用于存储图片、视频、文档等非结构化数据。
阿里云OSS对象存储的使用和实现万能文件上传
==oss==是对象存储服务(Object Storage Service)的缩写,是一种分布式存储服务,用于存储和访问大规模数据。它提供了可靠、安全、低成本的数据存储解决方案,可以通过网络随时随地访问存储的数据。oss常用于存储图片、视频、文档等非结构化数据。
1、开通阿里云OSS对象存储服务(新用户可以免费试用三个月)
https://www.aliyun.com/product/oss?spm=5176.8465980.unusable.ddetail.7df51450v1aNb1
1.1、点击免费试用并选择自己想要使用的服务
1.2、咱们这里选择使用第一个存储服务,然后点击立即试用
2、创建存储空间,获取bucketName和endpoint
存储空间(Bucket)是用于存储对象(Object)的容器。在上传任意类型的Object前,您需要先创建Bucket。
2.1、登录OSS管理控制台。
在左侧导航栏,单击Bucket列表,然后单击创建Bucket。
在创建Bucket面板,按如下说明配置必要参数。其他参数均可保持默认配置,也可以在Bucket创建完成后单独配置。然后单击确定。
2.2、Bucket命名规则
同一阿里云账号在同一地域内创建的Bucket总数不能超过100个。Bucket创建后,其名称无法修改。==Bucket命名规则==如下:
命名示例
Bucket名称的==正确示例==如下:
> - examplebucket1
> - test-bucket-2021
>- aliyun-oss-bucket
Bucket名称的==错误示例==以及错误的原因如下:
- Examplebucket1(包含了大写字母)
>- test_bucket_2021(包含了下划线)
> - aliyun-oss-bucket-(结尾包含了短划线)
2.3、成功创建并进入Bucket
2.4、进入Bucket后查看概览,记录下图信息
3、在阿里云网站上的个人中心配置Accesskey,查询accessKeyId和accessKeySecret。
3.1、进入AccssKey管理页面应该会出现下图提示,accessKeySecret为空,不用点击下载,直接确定即可
点击继续使用AccessKey
3.2、点击创建AccessKey
3.3、通过安全验证后可以看到生成的==accessKeyId和accessKeySecret==,大家下载csv文件或者复制下来,因为点击确定后==不再显示==accessKeySecret!!!
4、OSS的使用
4.1、导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
Java
4.2、创建对应的工具类AliOssUtil类,此代码是固定代码,直接CV即可。
package com.beiyou.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
@Data
//@AllArgsConstructor
@Component
//固定代码,CV直接使用
public class AliOssUtil {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
/**
* 文件上传
*
* @param bytes :传入的文件要转为byte[]
* @param objectName :表示在oss中存储的文件名字。
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(this.endpoint, this.accessKeyId, this.accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(this.bucketName, objectName, new ByteArrayInputStream(bytes));
} 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());
} 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());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
return stringBuilder.toString();
}
}
4.3、在该工具类中有四个属性,通过上面的步骤已经获得了我们上传图片到OSS所需要的四个参数:==bucketName、endpoint、accessKeyId、accessKeySecret==。这些属性需要我们手动在application.properties中配置。
# 配置阿里云OSS(application.properties)
aliyun.oss.bucketName = fpl1116-project
aliyun.oss.endpoint = oss-cn-zhangjiakou.aliyuncs.com
aliyun.oss.accessKeyId =
aliyun.oss.accessKeySecret =
# yml版(application.yml)
#aliyun:
# oss:
# bucketName: fpl1116-project
# endpoint: oss-cn-zhangjiakou.aliyuncs.com
# accessKeyId:
# accessKeySecret:
4.4、测试:创建业务代码(在本地项目基础上进行修改的大家可以去我的码云上查看项目完整结构)
UploadController
@RestController
@RequestMapping("/api/upload")
public class UploadController {
@Autowired
Uploadservice uploadService;
@PostMapping //文件上传
public String upload(@RequestBody UploadInfo uploadInfo){
return productService.upload(uploadInfo);
}
}
Uploadservice
@Service
public class Uploadservice {
private final AliOssUtil aliOssUtil;
public Uploadservice(AliOssUtil aliOssUtil) {
this.aliOssUtil = aliOssUtil;
}
public String upload(UploadInfo uploadInfo) {
//获取文件名称和编译码
String name=uploadInfo.getName();
String base64=uploadInfo.getBase64();
String[] base64Array = StrUtil.splitToArray(base64, "base64,");
byte[] bytes = Base64.decode(base64Array[1]);
//将文件名转为拼音
name = PinyinUtil.getPinyin(name, "");
//UUID加文件名防止文件覆盖
String newName=System.currentTimeMillis()+"_"+name;
return aliOssUtil.upload(bytes, newName);
}
}
更多推荐
所有评论(0)