开发微信小程序,可能遇到最蛋疼的一个问题就是 小程序不支持批量上传,一次只能上传一个文件。想要批量上传只能递归上传。通过以下方式即可实现 “批量上传”。
index.wxml
<!--index.wxml-->
<view class="container">
<block wx:for="{{images}}" wx:key="*this">
<view>
<image src="{{item}}" bindtap="handleImagePreview"></image>
</view>
</block>
<button bindtap="uploudImage"> 批量上传 </button>
</view>
index.js
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
images:[],
},
onLoad: function () {
},
uploudImage() {
const that = this;
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
console.log(res);
that.setData({
images: tempFilePaths,
});
var promise = Promise.all(tempFilePaths.map((tempFilePath, index) => {
return new Promise(function (resolve, reject) {
wx.uploadFile({
url: 'uploadurl',
filePath: tempFilePath,
name: 'name',
header: {},
formData: {},
success: function (res) {
resolve(res.data);
},
fail: function (err) {
console.log(err)
reject(new Error('failed to upload file'));
}
});
});
}));
promise.then(function (results) {
console.log(results); //返回上传成功的数据
}).catch(function (err) {
console.log(err);
});
}
})
},
})
参考 微信小程序 官方文档
本作品采用 知识共享署名 4.0 国际许可协议 进行许可。 转载无需与我联系,但须注明出处,注明文章来源