微信小程序上传多张图片功能是微信小程序开发中一个非常常见的功能,可以让用户在小程序中一次性上传多张图片,下面介绍一种实现多张图片上传的方法。
1.准备工作
在实现多张图片上传之前,我们需要准备一些工作:
- 我们需要在小程序端的页面中放置一个
input标签,用于触发图片选择; - 我们需要在小程序的
json文件中,开启chooseImage的权限; - 我们需要在小程序的
js文件中,引入wx.chooseImage方法,用于调用图片选择器。
2.实现多张图片上传
实现多张图片上传的步骤如下:
- 在页面的
input标签上绑定点击事件,当用户点击input标签时,调用wx.chooseImage方法; - 在
wx.chooseImage方法中,配置count参数,用于设置最多可以选择多少张图片; - 在
wx.chooseImage方法的success回调函数中,使用wx.uploadFile方法,上传图片到服务器。
3.代码示例
// 页面的input标签绑定点击事件
inputChooseImage: function () {
var that = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
that.setData({
tempFilePaths: tempFilePaths
});
// 上传图片
that.uploadImages(tempFilePaths);
}
})
},
// 上传图片
uploadImages: function (tempFilePaths) {
var that = this;
for (var i = 0; i < tempFilePaths.length; i++) {
wx.uploadFile({
url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[i],
name: 'file',
formData: {
'user': 'test'
},
success: function (res) {
var data = res.data
//do something
}
})
}
}
4.
以上就是,通过使用wx.chooseImage和wx.uploadFile方法,我们可以实现多张图片上传的功能。