這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)多張圖片上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
微信小程序上傳圖片每次只能上傳一張,所有很多朋友就會(huì)問想要多張圖片上傳怎么辦?
首先,我們來看一看wx.chooseImage(object)和wx.uploadFile(OBJECT)這兩個(gè)個(gè)api
示例代碼是這樣的:
wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'http://example.weixin.qq.com/upload', //僅為示例,非真實(shí)的接口地址 filePath: tempFilePaths[0], name: 'file', formData:{ 'user': 'test' }, success: function(res){ var data = res.data //do something } }) } })
登錄后復(fù)制
這里的示例代碼,是選擇圖片,然后上傳選中的圖片中的第一個(gè)圖片;
現(xiàn)在開始寫多張圖片上傳的例子
首先,我們還是要選擇圖片
wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths;//這里是選好的圖片的地址,是一個(gè)數(shù)組 } })
登錄后復(fù)制
然后在app.js中寫一個(gè)多張圖片上傳的方法,后面引入,你也可以寫在一個(gè)JS文件中,后面引入:
//多張圖片上傳 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,失敗也會(huì)執(zhí)行這里 }, fail: (res) => { fail++; console.log('fail:'+i+"fail:"+fail); }, complete: () => { console.log(i); i++; if(i==data.path.length){ //當(dāng)圖片傳完時(shí),停止調(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); } } }); }
登錄后復(fù)制
多張圖片上傳的方法寫好了,下面就是引用:
var app=getApp(); Page({ data:{ pics:[] }, choose:function(){//這里是選取圖片的方法 var that=this; wx.chooseImage({ count: 9-pic.length, // 最多可以選擇的圖片張數(shù),默認(rèn)9 sizeType: ['original', 'compressed'], // original 原圖,compressed 壓縮圖,默認(rèn)二者都有 sourceType: ['album', 'camera'], // album 從相冊(cè)選圖,camera 使用相機(jī),默認(rèn)二者都有 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){ } })
登錄后復(fù)制
完結(jié)。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,更多相關(guān)內(nèi)容請(qǐng)關(guān)注PHP中文網(wǎng)!
相關(guān)推薦:
以上就是微信小程序多張圖片上傳功能的實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注有卡有網(wǎng)。