小程式上傳多張圖片
阿新 • • 發佈:2019-02-09
效果圖:
單個檔案上傳
如果需求是後端那邊需要接收的是一個檔案陣列型別的 那麼單個檔案上傳的就用不了
view:
<view style='width:100%;'> <view wx:for="{{tempFilePaths}}"wx:key="{{index}}"> <image src='{{item}}' class="upload" data-id='{{index}}' bindlongtap='deleteImg'></image> </view> <image src='/images/upload.png' class="upload" bindtap='uploadImg'></image> </view>
js
var app = getApp(); var api = app.globalData.api; uploadImgSubmit: function () {//這裡觸發圖片上傳的方法 var that = this; var files = that.data.tempFilePaths; var host = api + 'api/wx/localeRecord/uploadImg'; this.uploadimgs({ url: host,//這裡是你圖片上傳的介面 path: files//這裡是選取的圖片的地址陣列 }); }, //多張圖片上傳 uploadimgs:function (data) { var that = this, i = data.i ? data.i : 0, success = data.success ? data.success : 0, fail = data.fail ? data.fail : 0; var userId = app.user.userId; wx.uploadFile({ url: data.url, filePath: data.path[i], name: 'files', formData: { 'dataId': boothId, 'userId': userId, 'param': 'LICENSE' }, success: (resp) => { success++; that.setData({ dataId: resp.data }) console.log(resp) console.log(that.data.dataId); //這裡可能有BUG,失敗也會執行這裡 }, fail: (res) => { fail++; console.log('fail:' + i + "fail:" + fail); }, complete: () => { console.log(i); i++; if (i == data.path.length) { //當圖片傳完時,停止呼叫 this.save();//上傳完後再執行的方法 console.log('執行完畢'); console.log('成功:' + success + " 失敗:" + fail); } else {//若圖片還沒有傳完,則繼續呼叫函式 console.log(i); data.i = i; data.success = success; data.fail = fail; that.uploadimgs(data); } } }); }, //圖片上傳本地 uploadImg:function(e){ var that=this; wx.chooseImage({ success: function (res) { var file = that.data.tempFilePaths; for (var i = 0; i < res.tempFilePaths.length;i++){ file.push(res.tempFilePaths[i]); } // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片 that.setData({ tempFilePaths: file }) } }) },