开发思路:
串行上传:在前端逐个上传图片,并等待上一个图片上传成功后再上传下一个图片,以保持上传顺序。
刚开始开发是通过一个for循环依次上传,没有考虑到可能因为图片大小、网络等原因导致后端返回的url顺序不一致,可以理解成多并发上传的时候而导致的顺序问题
代码大致实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| uploadAllPics(selectedImages, index) {
const { fileListPicStorage = [] } = this.data const { fileList = [] } = this.data return new Promise((resolve, reject) => { if (index >= selectedImages.length) { resolve() return } console.log(selectedImages) const image = selectedImages[index] console.log(image) wx.uploadFile({ url: app.globalData.url + app.globalData.apiVersion + '/upload', filePath: image.url, name: 'file', header: { 'Content-Type': 'multipart/form-data', token: wx.getStorageSync('token'), }, success: res => { console.log('图片上传成功', res) let data = JSON.parse(res.data) fileList.push(data.data.result) fileListPicStorage.push({ url: '******' + data.data.result, }) this.setData({ fileList, fileListPicStorage }) this.uploadAllPics(selectedImages, index + 1) .then(resolve) .catch(reject) }, fail: error => { console.error('图片上传失败', error)
this.uploadAllPics(selectedImages, index + 1) .then(resolve) .catch(reject) }, }) }) },
async afterRead(event) { app.showLoading('图片上传中') const that = this const { file } = event.detail console.log(file) try { await this.uploadAllPics(file, 0) console.log('所有图片上传完成') wx.hideLoading() } catch (error) { console.error('图片上传失败', error) } },
|