前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微信小程序实现图片上传限制数量和删除

微信小程序实现图片上传限制数量和删除

作者头像
明知山
发布2020-09-03 10:53:53
3.5K2
发布2020-09-03 10:53:53
举报
文章被收录于专栏:前端开发随笔前端开发随笔
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码语言: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
      })
    }
  }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档