微信提供了文件上傳的方法wx.uploadFile來上傳我們的圖片
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 } }) }})但是針對多圖上傳微信沒有給出相應的方法來解決,如此我們只能消耗我們程序猿的腦細胞來解決了,最開始我使用了for循環來循環上傳我的圖片,恰好本人是蘋果手機所以上傳是沒有問題的,本以為輕松解決了這個問題但是提交到測試以后坑了。測試MM說他那里提示上傳失敗。
于是借來測試手機打印出來錯誤消息
uploadFile:fail:the same task is working
wx.uploadFile不能并行,因為wx.uploadFile是一個異步函數,所以循環的時候在安卓手機上會出現并行
所以上面的通過循環wx.uploadFile方法進行多圖上傳肯定是不能行的了,既然不能并行我們是不是可以讓wx.uploadFile執行完后再執行wx.uploadFile了。看下修改后的代碼
這里為上傳圖片的方法,在里面作出判斷上傳完成以后重復調用upload_img
var img_index = 0;//上傳帶第幾張var image_list1 = new Array();//上傳圖片var upload_img = function (that, file_name) { that.setData({ hidden: false }); wx.uploadFile({ url: '', filePath: file_name, name: 'file', success: function (res) { //此處判斷是否上傳成功 var obj = JSON.parse(res.data); if (obj.ret_code == 1) { //上傳成功以后將上傳成功的圖片加入數組顯示出來,這樣可以避免沒有上傳成功的圖片就不顯示 var uploads = new Array(); var image_list = new Array(); //加入返回值 uploads = that.data.upload; uploads.push(obj.data); //加入圖片 image_list = that.data.tempFilePaths; image_list.push(file_name); that.setData({ upload: uploads, tempFilePaths: image_list }); //上傳成功一次img_index+1,下面再次調用upload_img上傳圖片就可以直接傳image_list1[img_index],也就是下一張圖片的鏈接 img_index = img_index + 1; //這里需要作出判斷圖片是否上傳完成,如果完成則取消緩沖框hidden if (img_index < image_list1.length) { upload_img(that, '' + image_list1[img_index]); } else { that.setData({ hidden: true }); } //刷新界面 that.update(); } else { that.setData({ hidden: true }); utils.show_toast(obj.msg); } }, fail: function (res) { that.setData({ hidden: true }); utils.show_toast('加入失敗'); } })}選擇圖片方法
if (that.data.tempFilePaths.length < 9) { wx.chooseImage({ count: 9 - that.data.tempFilePaths.length, // 最多可以選擇的圖片張數,默認9 sizeType: ['compressed'], // original 原圖,compressed 壓縮圖,默認二者都有 sourceType: ['album', 'camera'], // album 從相冊選圖,camera 使用相機,默認二者都有 success: function (res) { // success img_index = 0; image_list1=new Array(); //將選擇的圖片放入要上傳的數組中 for (var i = 0; i < res.tempFilePaths.length; i++) { console.log(i + ';' + res.tempFilePaths[i]); image_list1.push(res.tempFilePaths[i]); } //最開始上傳第一張圖片 upload_img(that, '' + image_list1[img_index]); }, fail: function () { utils.show_toast('選取失敗'); } }) } else { utils.show_toast('當前最多只能選擇9張圖片'); }通過上面的代碼就可以完成多圖上傳了,這樣也避免了Android手機報錯的漏洞
這里封裝了一個錯誤消息彈窗避免寫重復的代碼
utils.show_toast(‘當前最多只能選擇9張圖片')//彈窗 function show_toast(text) { wx.showToast({ title: text, icon: ‘success', duration: 2000 }); }以上所述是小編給大家介紹的微信多圖上傳解決android多圖上傳失敗問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答