微信小程序:多張圖片上傳


最近在寫小程序的相冊,需要多張圖片的上傳。因為小程序不支持數組的多張圖片同時上傳,然后根據自己的需求+借鑒網上各位大神的案例,總算搞定。分享下,不足之處,多多指教哦

頁面wxml:

<form bindsubmit="formSumbmit" bindreset="formReset">
<view class="modal-content">
<view class="modal-photo">
<view class="photo-img">
<view wx:for="{{img_arr}}" wx:key="key">
<image src='{{item}}'></image>
</view>
</view>
</view>
</view>
<view class="modal-footer">
<view class="btn-confirm" ><button formType="submit" style="color:#00d000;">確定</button></view>
</view>
</form>

Ps:::img_arr:為存放上傳的多張圖片的數組,使用for和自動換行顯示出來

將本地圖片上傳js:

upimg: function () {
console.log('上傳圖片');
var that = this;
if (that.data.img_arr == null) {
console.log('null張');
wx.chooseImage({
count: 9, //最多可以選擇的圖片張數,默認為9
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
success: function (res) {
console.log(res);
that.setData({
img_arr: res.tempFilePaths //concat
});
}
})
}
},

form表單提交,引用跳轉:

formSumbmit: function (e) {
console.log('對話框確認按鈕點擊事件');
console.log(e);

var that = this;
var data = [];
data.photo_info = e.detail.value.photo_info;
data.timestamp = Date.parse(new Date()) / 1000; //當前時間戳
data.i = 0;
that.upload(data);
},

ok,開始將文件上傳服務器:

upload: function (e) {
console.log('上傳圖片至服務器');
var photo_info = e.photo_info;
var timestamp = e.timestamp;
var i = e.i;
var that = this;
var length = that.data.img_arr.length;
//for (var i = 0; i < length; i++) {//循環遍歷圖片 //ps::這里也可以使用for循環方式一個個上傳,但是因為網絡等原因,不能很好地控制,故改用這種重新調用的方式來完成
var openid = app.globalData.openid;
wx.uploadFile({
url: '',//自己的接口地址
filePath: that.data.img_arr[i],
name: 'name',
formData:({//上傳圖片所要攜帶的參數
openid: openid,
photoInfo: photo_info,
timestamp: timestamp,
uploadName: 'name' //上傳name
}),
success: function (res) {
console.log(res);
if (res) {
console.log("返回的參數信息" + res.data);
wx.showToast({
title: '上傳中...',
duration: 3000,
icon: 'loading'
});
}
},
complete:function(){
console.log(i);
i++;
if(i == length){ //當圖片傳完時,停止調用
console.log('成功');
wx.showToast({
title: '上傳成功!',
duration: 1500,
success: function(){
that.hideModal();
}
});
}else {
e.photo_info = photo_info;
e.timestamp = timestamp; //當前時間戳
e.i = i;
that.upload(e); //ps::這里也可以使用for循環方式一個個上傳,但是因為網絡等原因,不能很好地控制,故改用這種重新調用的方式來完成
}
}
})
//}
},

搞定

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM