背景: 用户头像信息存储在阿里云
安装并引入ali-oss
npm install ali-oss
import OSS from 'ali-oss'
创建存储对象并将图片上传
createOss(){
const endpoint = this.OssInfo?.endpoint
const region = endpoint.replace('.aliyuncs.com', '')
const bucket = this.OssInfo?.image?.bucket
const { accessKeyId, secretAccessKey, sessionToken } = this.AliyunInfo
let client = new OSS({
region,
accessKeyId: accessKeyId,
accessKeySecret: secretAccessKey,
bucket: bucket,
stsToken: sessionToken,
secure: true,
})
return client;
},
async compressorImage(file){
const client = this.createOss(file)
const cdnHost = this.OssInfo?.image?.cdnHost
const fileName = file.name
const suffix = fileName.substr(fileName.indexOf("."))
const timestampStr = timestamp()
const storeAs = 'xxx/'+timestampStr+suffix
const IMAGE_SIZE = 1 * 1024 * 1024
let compressImage = file
return new Promise( (resolve) => {
client.put(storeAs, compressImage).then(() => {
resolve(cdnHost+storeAs)
}).catch(() => {
resolve(false)
})
})
}
},
需要注意的是,在上传之前需要获取对应的 上传域和阿里云key
async getOssInfo(){
const resOssInfo = await this.$axios({
method: 'POST',
url: `${this.PUB_BASE_URL}/api/xxx/xxx/xxx`,
data: {
request_header: this.HEADER,
request_data: {
version: 11
}
}
})
if(resOssInfo.code === 0){
this.OssInfo = resOssInfo?.data?.info ? resOssInfo.data.info : {}
}
},
async getAliyunInfo(){
const resAliyunInfo = await this.$axios({
method: 'POST',
url: `${this.PUB_BASE_URL}/api/api/xxx/xxx/xxx`,
data: {
request_header: this.HEADER,
request_data: {
version: 11
}
}
})
if(resAliyunInfo.code === 0){
this.AliyunInfo = resAliyunInfo?.data?.aliyunInfo ? resAliyunInfo.data.aliyunInfo : {}
}
},