阿里云存储OSS使用及文件上传【示例:头像上传】
一、对象存储OSS
为了解决海量数据存储与弹性扩容,所以我们采用云存储的解决方案;
1.1开通“对象存储OSS”服务
(1)申请阿里云账号
(2)实名认证
(3)开通“对象存储OSS”服务
(4)进入管理控制台
1.2创建Bucket
选择:标准存储、公共读、不开通
二、创建Maven项目
2.1pom
<dependencies>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2.2找到编码时需要用到的常量值
(1)endpoint------>在Bucket中概述的访问域名
(2)bucketName------>在创建的Bucket中的名字
(3)accessKeyId------>在阿里云,点击头像中的AccessKey查看
(4)accessKeySecret------>在阿里云,点击头像中的AccessKey查看
三、开始
3.1第一步:配置文件
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=你的
aliyun.oss.file.keyid=你的
aliyun.oss.file.keysecret=你的
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=你的
3.2第二步:创建配置文件工具类
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件内容
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
//定义公开静态常量
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
3.3第三步:创建controller
@PostMapping
public R uploadOssFile(MultipartFile file){
//获取上传文件 MultipartFile
//返回山传到oss的路径
String url = ossService.uploadFileAvatar(file);
return R.ok().data("url",url);
}
3.4第四步:业务层service处理逻辑
@Override
public String uploadFileAvatar(MultipartFile file) {
// 工具类获取值
String endpoint = ConstantPropertiesUtils.END_POIND;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 获取文件输入流
InputStream inputStream = file.getInputStream();
// 获取到文件的名称
String filename = file.getOriginalFilename();
// 1、在文件名称里面添加随机唯一的值
String uuid = UUID.randomUUID().toString().replace("-","");
filename = uuid+filename;
// 2、把文件按照日期进行分类 例如 2021/11/11
// 获取当前日期
String dataPath = new DateTime().toString("yyyy/MM/dd");
filename = dataPath + "/" + filename;
// 调用oss方法实现上传
ossClient.putObject(bucketName, filename, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
// 把上传之后文件路径返回
// 需要把上传到阿里云oss路径手动拼接出来
//https://sys-gulistudent.oss-cn-beijing.aliyuncs.com/%E5%A3%81%E7%BA%B8.jpg
String url = "https://"+bucketName+"."+endpoint+"/"+filename;
return url;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
四、示例:头像上传
4.1上传组件ImageCropper和PanThumb
到我的资源中下载【上传组件使用到的组件.zip】
4.2前端添加文件上传组件
template:
<!-- 讲师头像 -->
<el-form-item label="讲师头像">
<!-- 头衔缩略图 -->
<pan-thumb :image="teacher.avatar"/>
<!-- 文件上传按钮 -->
<el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
</el-button>
<!--
v-show:是否显示上传组件
:key:类似于id,如果一个页面多个图片上传控件,可以做区分
:url:后台上传的url地址
@close:关闭上传组件
@crop-upload-success:上传成功后的回调 -->
<image-cropper
v-show="imagecropperShow"
:width="300"
:height="300"
:key="imagecropperKey"
:url="BASE_API+'/admin/oss/file/upload'"
field="file"
@close="close"
@crop-upload-success="cropSuccess"/>
</el-form-item>
引入组件模块:
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
注入组件
export default {
components: { ImageCropper, PanThumb },
data(){
teacher:{
...
avatar: ''
},
//上传弹框组件是否显示
imagecropperShow:false,
imagecropperKey:0,//上传组件key值
BASE_API:process.env.BASE_API,//接口API地址
saveBtnDisabled: false // 保存按钮是否禁用,
},
methods: {
//关闭上传弹框的方法
close(){
this.imagecropperShow = false;
//上传组件初始化
this.imagecropperKey = this.imagecropperKey + 1;
},
//上传成功方法
cropSuccess(data){
this.imagecropperShow = false;
//上传之后接口返回图片地址
this.teacher.avatar = data.url;
//上传组件初始化
this.imagecropperKey = this.imagecropperKey + 1;
},
}
}