1.vue 使用对象存储OSS(用的Browser.js简单上传)
1.1先安装oss
npm i ali-oss -D (安装到生产依赖)
package.json安装成功显示
"ali-oss": "^6.17.1",
1.2 在页面中引入oss
import OSS from "ali-oss";
2.使用OSS
2.1
this.client = new OSS({
//我这边根据后台返回对应的region、accessKeyId、accessKeySecret、stsToken、bucket,什么意思可参考具体文档https://help.aliyun.com/document_detail/383950.html?spm=a2c4g.64041.0.0
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
accessKeyId: res.data.data.accessKeyId,
accessKeySecret: res.data.data.accessKeySecret,
region: res.data.data.region,//服务器集群地区
stsToken: res.data.data.stsToken,
bucket: res.data.data.bucket
});
2.2
// file是根据上传图片返回的数据进行处理,后面this.client.put要用
const tmpCnt = file.file.name.lastIndexOf("."); // 获取.的下标
const uploadFileName = file.file.name.substring(0, tmpCnt); // 获取文件名
const exName = file.file.name.substring(tmpCnt + 1); // 获取后缀名
// 判断上传的类型格式
const names = ["jpg","jpeg", "webp","png","bmp","exe","yml","txt"];
if (names.indexOf(exName) < 0) {
this.$message.error("不支持的格式!");
return false;
}
//定义日期方便服务器目录存储
const date = new Date();
const yyyyMMdd = date.getFullYear() + "年" + (date.getMonth() + 1) +"月" + date.getDate() + "日" + "/";
//生成唯一的目录
const fileName = uploadFileName + "/" + yyyyMMdd + guid() + "." + exName; // 获取文件名
解释:guid()封装的生成唯一值的工具类(单独封装供上面使用,这里解释一下guid()是干什么用的)
function S4 () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
export const guid = () => {
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
2.3 主要this.client.put()上传生成的目录fileName和文件file.file
this.client.put(fileName, file.file).then(res => {
addAttachmentList([
{
bucketName: this.bucketName,
objectName: fileName,
name: res.name,
suffix: exName
}
]).then(res => {
// 1 上传概要背景 2 添加详情多个图片 3 添加富文本图片
if (type == 2) {
let detailObj = {
cover: res.data.data[0]
};
this.detailCoverID.push(detailObj);
} else if(type == 1) {
this.coverId = res.data.data[0];
}else if(type == 3){
this.descriptionID = res.data.data[0];
}
});