关于阿里云的配置就不说了(后台会配置好并在接口中返回给前端相关配置信息)
正常来说获取到上传图片信息,调用封装方法
async getSelectFileImg(val) {
this.params.businessLicenseUrl = await getTempOssData(val);
},
封装方法,只不过这里是单张上传逻辑
其中先从后端获取到阿里云配置的所有信息,一同返给后端
// 单张图片批量上传到阿里OSS并返回临时链接
export async function getTempOssData(val) {
console.log('上传的文件', val);
const tempuuid = generateUUIDWithoutDashes()
let otherUrl = `${tempuuid}.${val.tempFiles[0].extname}`
const res = await uni.$http.get('/oss/getOssTokenByAccessID')
const data = res.data.data;
const {
accessKeyId,
dir,
expiration,
host,
policy,
signature
} = data
const uploadResult = await new Promise((resolve, reject) => {
uni.uploadFile({
url: host,
filePath: val.tempFilePaths[0],
name: 'file',
formData: {
key: `${dir}${otherUrl}`,
OSSAccessKeyId: accessKeyId,
policy,
signature,
},
success: res => {
console.log('OSS上传结果', res, tempuuid);
if (res.statusCode == 204) {
console.log('临时链接', `${host}/${dir}${otherUrl}`);
resolve(`${host}/${dir}${otherUrl}`)
} else {
uni.$showMsg('图片上传失败,请删除后重新上传')
reject(new Error('上传失败'));
}
},
fail(err) {
uni.$showMsg(err)
reject(err);
}
})
})
return uploadResult
}
但是如果是说多张图片的话,使用遍历即可
uni.chooseMedia({
mediaType: ['image', 'video'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success: (val) => {
uni.$http.get('/oss/getOssTokenByAccessID').then((res) => {
const data = res.data.data;
const { accessKeyId, dir, expiration, host, policy, signature } = data;
for (let i = 0; i <= val.tempFiles.length - 1; i++) {
let type = val.tempFiles[i].tempFilePath.split('.');
let tempuuid = generateUUIDWithoutDashes();
uni.uploadFile({
url: host,
filePath: val.tempFiles[i].tempFilePath,
name: 'file',
formData: {
key: `${dir}${tempuuid}.${type[type.length - 1]}`,
OSSAccessKeyId: accessKeyId,
policy,
signature
},
success: (res) => {
if (res.statusCode == 204) {
this.params.url.push({ url: `${host}/${dir}${tempuuid}.${type[type.length - 1]}`, type });
} else {
uni.$showMsg('上传失败,请删除后重新上传');
}
},
fail(err) {
uni.$showMsg(err);
}
});
}
});
}
});