微信小程式上傳多張圖檔(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,就再次調用