微信小程序递归上传图片

2022-05-05 20:09:48 浏览数 (2)

代码语言:javascript复制
     <view class="col">
            <view class="file" wx:for="{{fileList}}" wx:key="index">
                <image mode="aspectFill" src="{{item}}" />
                <view class="del" data-index="{{index}}" bindtap="delFile">
                    <image mode="widthFix" src="https://sucai.suoluomei.cn/sucai_zs/images/20200521115446-38.png" />
                </view>
            </view>
            <view class="update" wx:if="{{upload}}" bindtap="uploadFile">
                <image mode="widthFix" src="https://sucai.suoluomei.cn/sucai_zs/images/20200521103739-37.png" />
                <text wx:if="{{photo == 0}}">添加照片</text>
                <text wx:if="{{photo == 1}}">{{count}}/5</text>
            </view>
        </view>
代码语言:javascript复制
 data: {
  fileList: [],
  photo: 0,
  count: 0,
  upload: true
}
// 上传图片
  uploadFile() {
    wx.chooseImage({
      count: 5 - this.data.fileList.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.getpublish(res.tempFilePaths, 0)
      }
    })
  },
  // 递归上传
  getpublish(list, i) {
    wx.showLoading({
      title: '正在上传第'   (i   1)   '张',
    })
    wx.uploadFile({
      url: "http://uploadFile",
      filePath: list[i],
      name: 'file',
      formData: {
        key: 'key'
      },
      success: (res) => {
        var info = JSON.parse(res.data)
        var array = this.data.fileList
        array.push(info.info.url)
        this.setData({
          fileList: array
        })
        if (i   1 == list.length) {
          wx.showToast({
            title: '上传成功',
          });
        }
        wx.hideLoading()
        if (  i < list.length) {
          this.getpublish(list, i);
        }
        this.hideUpload()
      },
    })
  },
  // 删除图片
  delFile(e) {
    var index = e.currentTarget.dataset.index
    var list = this.data.fileList
    list.splice(index, 1)
    this.setData({
      fileList: list
    })
    this.hideUpload()
  },

  // 隐藏上传控件
  hideUpload() {
    var length = this.data.fileList.length
    if (length == 0) {
      this.setData({
        photo: 0,
        count: 0
      })
    } else {
      this.setData({
        photo: 1,
        count: length
      })
    }
    // 隐藏上传图片
    if (length >= 5) {
      this.setData({
        upload: false
      })
    } else {
      this.setData({
        upload: true
      })
    }
  }

0 人点赞