小程序 上传图片(多张、多次上传),预览图片 删除图片

做过小程序的都会碰到一个问题,那就是上传图片,单张图片没有难度,参照官方文档就行了。那多张图片上传(或者多次上传)呢。

我的解决方法涉及了一个概念--递归。

直接上代码, wxml

<!-- 详情的车辆图片 -->
<view class='conf-wrap'>
  <view wx:for="{{imgListUrls}}" class='up-img-wrap' wx:key="{{index}}">
    <!-- 图片 -->
    <image src='{{item}}' class='up-img' mode='aspectFill' bindtap='previewImg' data-id='{{index}}'></image>
    <!-- 删除按钮 -->
    <image class="del-img" mode='aspectFill' src="{{delImg}}" bindtap='delImg' data-id='{{index}}'></image>
  </view>
  <!-- 图片上传按钮 -->
  <view class='up-img-wrap' wx:if="{{imgListUrls.length <3}}"><image bindtap='chooseImg' src='../images/seekcar/upload.png' class='up-img' ></image> </view>
  <button class='save-btn' bindtap='uploadImg'> 保存 </button>
</view>

wxss,

.conf-wrap{width:91.7%;margin:50rpx auto;}
.save-btn{width:100%;margin-top:80rpx;background-color:#000;color:#fff;font-size:32rpx;border-radius:0rpx;height:90rpx;line-height:90rpx;}
.up-img-wrap{width:228rpx;height: 188rpx;display: inline-block;text-align: center;position: relative;}
.up-img{width: 188rpx;height: 188rpx;display: inline-block;}
.del-img{position: absolute;top:-15rpx;left: 185rpx;width: 40rpx;height: 40rpx;}

app.js  因为使用了global 变量来储存数据供别的页面调用。

以下三个变量都在 globalData 内
idList: [], // 储存上传图片的id的list displayImgList: [], // 储存上传图片url地址的list tmpImgList:[],// 上传图片时图片缓存的list

js 

const app = getApp()
Page({
  /**
   * Page initial data
   */
  data: {
    imgListUrls:app.globalData.tmpImgList,
    imgListUrlsCp:[],
    hasImgUpload:false, 
    delImg:'../images/seekcar/del_img.png'
  },

  // 调用相机或者本地相册获取图片
  chooseImg:function(e){
    var that = this
    wx.chooseImage({
      count:(3-that.data.imgListUrls.length),
      sizeType:['original','compressed'],
      success:function(res){
        var newList = app.globalData.tmpImgList
        if (app.globalData.tmpImgList.length > 0) {
          newList = newList.concat(app.globalData.tmpImgList)
        }    
        newList = that.data.imgListUrls.concat(res.tempFilePaths)
        that.setData({
          imgListUrls: newList,
          imgListUrlsCp : newList,
          hasImgUpload:true
        })
        app.globalData.tmpImgList = newList.toString().split(',')
      },
      fail:function(e){
        wx.showToast({
          title: e.errMsg,
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.hideToast()
        }, 2000)
      }
    })
  },
  // 上传图片到服务器
  uploadImg:function(){
    var that = this
    // 如果有图片
    if(that.data.imgListUrlsCp.length > 0){
      wx.uploadFile({
        url: app.globalData.urlHead+'/api/v2/upload/orderConfig',
        filePath: that.data.imgListUrlsCp[0],
        name: 'uploadFile',
        formData:{
          token:app.globalData.token
        },
        success:function(res){
          var dataRcv = JSON.parse(res.data)
          // console.log(res)
          if(dataRcv.code == 0){
            // push id 到list中
            app.globalData.idList.push(dataRcv.data.id[0]) 
            // push img url 到 list 中
            app.globalData.displayImgList.push(dataRcv.data.url[0])
            // 去掉数组中第一个值
            that.data.imgListUrlsCp.shift()
            // 检测是否需要递归
            if (that.data.imgListUrlsCp.length > 0) {
              that.uploadImg()
            }else{
              wx.navigateBack({
                delta:1
              })
            }
          }
        }
      })
    }else{
      if(that.data.hasImgUpload == false){
        wx.showToast({
          title: '上传至少一张图片',
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.hideToast()
        }, 2000)
        return;
      }
      wx.navigateBack({
        delta:1
      })
    }
  },

  // 预览图片
  previewImg:function(e){
    wx.previewImage({
      current: app.globalData.tmpImgList[e.currentTarget.dataset.id],
      urls: app.globalData.tmpImgList,
    })
  },

  // 删除图片
  delImg:function(e){
    //获取数据绑定的data-id的数据
    var currIndex = e.currentTarget.dataset.id
    let images = app.globalData.tmpImgList
    images.splice(currIndex, 1);
    this.setData({
      // imgListUrlsCp: images,
      imgListUrls:images
    })
    app.globalData.tmpImgList = images
    app.globalData.displayImgList = images
    if(app.globalData.tmpImgList.length>0){
      this.setData({
        hasImgUpload:true
      })
    }
  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function () {
    var that = this
    that.setData({
      imgListUrls: app.globalData.tmpImgList,
      textValue: app.globalData.textArea
    })
    app.globalData.displayImgList = []
  },

})
原文地址:https://www.cnblogs.com/ming-os9/p/10869782.html