需求:小程序端上传图片,可一次传多张照片、预览、删除。
问题:vant写的对我这种没有基础的人来说,确实有点头疼,参考了这篇参考链接,然后根据需求改了改。
实现结果:
代码:
wxml:
<!-- 传图片 -->
<view class="addImage" ><van-uploader file-list="{{ fileList }}" accept="image" max-count="9" multiplebind:after-read="afterRead" bind:delete="deleteImg" bind:before-read="beforeRead"deletable="{{ true }}"preview-size="{{(width+50)/4 }}" />
</view>
js:后端部分,请根据自己后端接口修改
//文件读取完成后
afterRead(event) {const { file } = event.detail; var that = thisconst fileList = that.data.fileList//获得这次上传的图片数量,上传时避免重复上传之前传过的文件const thisNum = file.length const beforeNum = fileList.length const totalNum = thisNum + beforeNum//还没上传时将选择的图片的上传状态设置为加载 for (let j = 0; j < thisNum; j++) {file[j].status='uploading'fileList.push(file[j])}that.setData({ fileList })// console.log('fileList',that.data.fileList)// console.log('file',file)//上传服务器for (let i = beforeNum; i < totalNum; i++) {that.uploadImg(i,that.data.fileList[i].url )}},
js:
uploadImg(fileListIndex,fileURL) {var that = this//上传文件const filePath = fileURL // 小程序临时文件路径// console.log("filePath",filePath)wx.uploadFile({url: '后端地址',filePath: filePath,name: 'file',header: {"Content-Type": "multipart/form-data",},formData: { fileType:'image',reName:'true',thumbnail:'true'},success(res) {var tem = JSON.parse(res.data)// 上传完成需要更新 fileListthat.setData({[`fileList[${fileListIndex}].url`]: tem.data.fileUrl,[`fileList[${fileListIndex}].status`]: 'done'})wx.showToast({ title: '上传成功', icon: 'none' })},fail: function (res) {console.log("file upload fail")},})},