使用 Promise.all()等待所有图片上传完成之后回调,弊端:网络不好的情况下可能会终止,最好还是和后端要多图上传接口(如果他有空)
async add() {
uni.showLoading({
title: "上传中"
})
uni.chooseImage({
count: 20,
sizeType: ['original', 'compressed'],
sourceType: ['album'],
success: async function(res) {
console.log(res.tempFilePaths);
let arr = []
let promiseArr = []
res.tempFilePaths.forEach((item, index) => {
promiseArr.push(new Promise((resolve, reject) => {
uni.uploadFile({
url: IMG_UP_URL,
filePath: item,
name: 'file',
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
if (uploadFileRes.data) {
let object = JSON.parse(
uploadFileRes.data)
console.log("图片" + index +
"上传完成");
resolve(object?.data?.path ||
"")
} else {
reject()
}
},
});
}))
})
let p = () => Promise.all(promiseArr)
arr = await p()
console.log("上传图片数组", arr);
uni.hideLoading()
// uploadImgToClass({
// id:this.id,
// arr
// })
}
});
},