封装:
import OSS from "ali-oss";
import Vue from 'vue'
// 初始化 OSS
const ossClient = new OSS({
accessKeyId: "LTAI4GHSEsBd5hqbSVnHh1R5", // 查看你自己的阿里云KEY
accessKeySecret: "XuUXzaqUMWdxbZSMTi7RMiRv2temuG", // 查看自己的阿里云KEYSECRET
bucket: "yuyuhu", // 你的 OSS bucket 名称
region: "oss-cn-guangzhou", // bucket 所在地址,我的是 华北2 北京
});
Vue.prototype.$ossClient = ossClient
Vue.prototype.$putOssImg = function (file, flag = 1) {
console.log('file', file)
return new Promise((reslove) => {
// let fileName = file.name.substr(0, file.name.lastIndexOf("."));
let dateMain = new Date();
let year = dateMain.getFullYear();
let month = dateMain.getMonth() + 1;
month = month < 10 ? '0' + month : month
let date = new Date().getTime();
let fileNames = `${date}_${file.name}`; // 拼接文件名,保证唯一,这里使用时间戳+原文件名
this.$ossClient.put("uploads/" + year + month + '/' + fileNames, file).then((res) => {
if (res.res.statusCode === 200) {
let url = res.res.requestUrls[0];
reslove(url);
if (flag == 0) return;
this.$message({
message: "上传成功",
type: "success",
});
} else {
this.$message("上传失败");
}
});
})
}
使用:
async upLoadRequest({ file }) {
let url = await this.$putOssImg(file);
this.form.goods_image = url;
},