微信小程序:多张图片上传

最近在写小程序的相册,需要多张图片的上传。因为小程序不支持数组的多张图片同时上传,然后根据自己的需求+借鉴网上各位大神的案例,总算搞定。分享下,不足之处,多多指教哦

页面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循环方式一个个上传,但是因为网络等原因,不能很好地控制,故改用这种重新调用的方式来完成
}
}
})
//}
},

搞定

原文地址:https://www.cnblogs.com/two-bees/p/10458208.html