效果图:
官方的api:https://developers.weixin.qq.com/miniprogram/dev/api/network-file.html#wxuploadfileobject
单个文件上传
如果需求是后端那边需要接收的是一个文件数组类型的 那么单个文件上传的就用不了
view:
<view style='width:100%;'> <view wx:for="{{tempFilePaths}}"wx:key="{{index}}"> <image src='{{item}}' class="upload" data-id='{{index}}' bindlongtap='deleteImg'></image> </view> <image src='/images/upload.png' class="upload" bindtap='uploadImg'></image> </view>
js
var app = getApp(); var api = app.globalData.api; uploadImgSubmit: function () {//这里触发图片上传的方法 var that = this; var files = that.data.tempFilePaths; var host = api + 'api/wx/localeRecord/uploadImg'; this.uploadimgs({ url: host,//这里是你图片上传的接口 path: files//这里是选取的图片的地址数组 }); }, //多张图片上传 uploadimgs:function (data) { var that = this, i = data.i ? data.i : 0, success = data.success ? data.success : 0, fail = data.fail ? data.fail : 0; var userId = app.user.userId; wx.uploadFile({ url: data.url, filePath: data.path[i], name: 'files', formData: { 'dataId': boothId, 'userId': userId, 'param': 'LICENSE' }, success: (resp) => { success++; that.setData({ dataId: resp.data }) console.log(resp) console.log(that.data.dataId); //这里可能有BUG,失败也会执行这里 }, fail: (res) => { fail++; console.log('fail:' + i + "fail:" + fail); }, complete: () => { console.log(i); i++; if (i == data.path.length) { //当图片传完时,停止调用 this.save();//上传完后再执行的方法 console.log('执行完毕'); console.log('成功:' + success + " 失败:" + fail); } else {//若图片还没有传完,则继续调用函数 console.log(i); data.i = i; data.success = success; data.fail = fail; that.uploadimgs(data); } } }); }, //图片上传本地 uploadImg:function(e){ var that=this; wx.chooseImage({ success: function (res) { var file = that.data.tempFilePaths; for (var i = 0; i < res.tempFilePaths.length;i++){ file.push(res.tempFilePaths[i]); } // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 that.setData({ tempFilePaths: file }) } }) },