由于小程序一次只能上传一张图片,循环上传多张图片
核心代码如下:
<view class="pic">
<view class="one" bindtap="upload" data-img="img1">
<image class="upload_img1" src="/img/phone_upload.png"></image>
<view>点击上传手持身份证</view>
<image class="myimg" src="{{img1}}"></image>
</view>
<view class="one"></view>
<view class="one" bindtap="upload" data-img="img2">
<image class="upload_img1" src="/img/phone_upload.png"></image>
<view>点击上传带头像一面</view>
<image class="myimg" src="{{img2}}"></image>
</view>
<view class="one" bindtap="upload" data-img="img3">
<image class="upload_img1" src="/img/phone_upload.png"></image>
<view>点击上传带国徽一面</view>
<image class="myimg" src="{{img3}}"></image>
</view>
</view>
//上传图片
upload: function (e) {
var that = this;
var img = e.currentTarget.dataset.img;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: res => {
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 1000
})
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
let tempFilePaths = res.tempFilePaths[0];
if (img == "img1") {
that.setData({ img1: tempFilePaths })
that.my_img(0, tempFilePaths);
} else if (img == "img2") {
that.setData({ img2: tempFilePaths })
that.my_img(1, tempFilePaths);
} else if (img == "img3") {
that.setData({ img3: tempFilePaths })
that.my_img(2, tempFilePaths);
} else if (img == "img4") {
that.setData({ img4: tempFilePaths })
that.my_img(3, tempFilePaths);
} else if (img == "img5") {
that.setData({ img5: tempFilePaths })
that.my_img(4, tempFilePaths);
}
console.log(tempFilePaths)
}
})
},
my_img: function (i, content) {
var new_img = this.data.imgArr;
new_img[i] = content;
this.setData({
imgArr: new_img
})
}
uploadAll: function (userId) {
var uploadImgCount = 0;
var uploadArr = this.data.imgArr;
var url = app.globalData.api + 'wechat/uploadFile';
for (var i = 6; i >=0; i--) {
var j = i+1;
if (uploadArr[i]) {
wx.uploadFile({
url: url,
filePath: uploadArr[i],
name: 'file',
formData: {
userId:userId,
type:j
},
header: {"Content-Type": "multipart/form-data"},
success: function (res) {
uploadImgCount++;
//如果是最后一张,则隐藏等待中
if (uploadImgCount == 7) {
console.log("success")
wx.hideToast();
//上传所有图片
app.jump("/pages/d_home/d_home");
}
},
fail: function (res) {
wx.hideToast();
wx.showModal({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function (res) { }
})
}
});
} else {
uploadImgCount++;
}
}
},