微信小程序上传多张图片(wx.uploadFile)
场景:最近做微信小程序项目要实现文件上传的功能,解决方案是使用微信官方接口wx.uploadFile上传,真机调试遇到问题,当选择多张时,还是只上传了一张
解决方案:wx.uploadFile只接受一张图片url,所以采用了循环调用的方式
//上传图片
afterRead(event) {
// const { file } = event.detail;
this.data.file = event.detail.file
this.data.fileNameIndex = event.detail.index
this.data.fileIndex = 0 //每次唤起都将fileIndex重置为0
// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
this.uploadFile(this.data.file)
},
uploadFile(file) {
wx.uploadFile({
url: this.data.host + 'file/upload',
filePath: file[this.data.fileIndex].url,
header: {
'content-type': 'multipart/form-data'
},
name: 'file',
formData: { user: 'test', method: 'POST' },
success: (res) => {
// debugger
// 上传完成需要更新 fileList
// const { fileList = [] } = this.data;
this.data.fileList.push({ url: JSON.parse(res.data).data });
this.setData({ fileList:this.data.fileList });
this.data.imageUrlList.push(JSON.parse(res.data).data)
this.data.imageUrl = this.data.imageUrlList.join(",")
this.data.fileName.push(this.data.fileNameIndex)
},
fail(error) {
// debugger
},
complete: () => {
this.data.fileIndex = this.data.fileIndex + 1
if(this.data.fileIndex==file.length) {
}else{
this.uploadFile(this.data.file)
}
}
});
},
首先是在图片上传的回调函数中取得文件对象,然后调用uploadFile方法上传图片到服务器,关键的一步是每次上传后(不管是否成功),只要上传的次数少于文件对象的length,就再次调用