微信小程序上傳圖片每次只能上傳一張,所有很多朋友就會問想要多張圖片上傳怎么辦?
首先,我們來看一看wx.chooseImage(object)和wx.uploadFile(OBJECT)這兩個個api
示例代碼是這樣的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'http://example.weixin.qq.com/upload', //僅為示例,非真實的接口地址 filePath: tempFilePaths[0], name: 'file', formData:{ 'user': 'test' }, success: function(res){ var data = res.data //do something } }) } }) |
這里的示例代碼,是選擇圖片,然后上傳選中的圖片中的第一個圖片;
現(xiàn)在開始寫多張圖片上傳的例子
首先,我們還是要選擇圖片
1 2 3 4 5 6 |
wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths;//這里是選好的圖片的地址,是一個數(shù)組
} }) |
然后在app.js中寫一個多張圖片上傳的方法,后面引入,你也可以寫在一個JS文件中,后面引入:
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 |
//多張圖片上傳 function uploadimg(data){ var that=this, i=data.i?data.i:0, success=data.success?data.success:0, fail=data.fail?data.fail:0; wx.uploadFile({ url: data.url, filePath: data.path[i], name: 'fileData', formData:null, success: (resp) => { success++; console.log(resp) console.log(i); //這里可能有BUG,失敗也會執(zhí)行這里 }, fail: (res) => { fail++; console.log('fail:'+i+"fail:"+fail); }, complete: () => { console.log(i); i++; if(i==data.path.length){ //當圖片傳完時,停止調(diào)用 console.log('執(zhí)行完畢'); console.log('成功:'+success+" 失敗:"+fail); }else{//若圖片還沒有傳完,則繼續(xù)調(diào)用函數(shù) console.log(i); data.i=i; data.success=success; data.fail=fail; that.uploadimg(data); }
} }); } |
多張圖片上傳的方法寫好了,下面就是引用:
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 |
var app=getApp(); Page({ data:{ pics:[] }, choose:function(){//這里是選取圖片的方法 var that=this; wx.chooseImage({ count: 9-pic.length, // 最多可以選擇的圖片張數(shù),默認9 sizeType: ['original', 'compressed'], // original 原圖,compressed 壓縮圖,默認二者都有 sourceType: ['album', 'camera'], // album 從相冊選圖,camera 使用相機,默認二者都有 success: function(res){ var imgsrc=res.tempFilePaths; that.setData({ pics:imgsrc }); }, fail: function() { // fail }, complete: function() { // complete } })
}, uploadimg:function(){//這里觸發(fā)圖片上傳的方法 var pics=this.data.pics; app.uploadimg({ url:'https://........',//這里是你圖片上傳的接口 path:pics//這里是選取的圖片的地址數(shù)組 }); }, onLoad:function(options){
}
}) |