vue3 oss - sdk 上传图片
2021-08-26 本文已影响0人
ThisWu
vue3和vue2上传图片基本是一样的操作
一、操作步骤
2.封装相关oss对象,和文件名称
let OSS = require('ali-oss')
export const client = new OSS({
region: "oss-cn-*****",
accessKeyId: '*****',
accessKeySecret: '*****',
bucket: '*****',
})
export const random_name = `${random_string(6)}_${new Date().getTime()}`;
// export default OSS
function random_string(len) {
len = len || 32;
let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
let maxPos = chars.length;
let pwd = "";
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
3.使用,并上传:
import {client, random_name} from '@/utils/alioss'
// 上传方法封装
const upload = (res)=>{
return new Promise(function (resolve, reject){
let obj = {'image/jpeg':'jpeg', 'image/jpg':'jpg', 'image/png':'png'},
imaName = `${random_name}.${obj[res.raw.type]}`;
client.multipartUpload(imaName, res.raw).then(function (result) {
let _res = result.res;
if (_res.status === 200 && _res.statusCode === 200) {
resolve(`https://*****.*******.aliyuncs.com/${imaName}`)
}else{
reject(_res)
}
}).catch((err)=>{
reject(err)
})
})
}
// 调用, res是element-upload组件得到的组件文件 , res.raw才是真正的文件
upload(res).then(url=>{
// url 就是图片地址
})