微信小程序实现图片上传,预览,删除

wxml:

1     <view class='imgBox'>
2       <image class='imgList' wx:for="{{imgs}}"  wx:for-item="item" src='{{item}}' data-index="{{index}}" wx:key="*this" bindtap="previewImg">
3         <icon class='imgCancel' type="clear" size='25' data-index="{{index}}" catchtap="deleteImg"></icon>
4       </image>
5       <image src='../../images/ic_pic.png' bindtap='addImg' wx:if="{{isShowAdd}}" ></image>
6     </view>

wxss:

.imgBox{
  padding: 25rpx 0rpx;
}
.imgBox image{
  width: 200rpx;
  height: 200rpx;
  margin-right: 15rpx;
}
.imgBox .imgList{
  position: relative;
}
.imgBox .imgList .imgCancel{
position: absolute;
top: 0rpx;
right: 0rpx;
}

js:countNum 和 max值可根据自己的需求更改,但是二者的值须相同

Page({
  data: {
    isShowAdd:true,
    imgs: [],
    countNum:3, //设定一次性选择图片的上限值
    max:3 //设定上传图片总数的上限值,与countNum相同
  },    
//添加图片
  addImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: that.data.countNum, // 上传图片上限值
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs=that.data.imgs;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= that.data.max) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
            //上传图片达到上限count值时,隐藏添加按钮
            if (imgs.length >= that.data.max){
              that.setData({
                isShowAdd: false
              });
            }
          }
        }
        that.setData({
          imgs: imgs,
          countNum: that.data.max-imgs.length //每增加一张图片,动态计算还可添加照片的数量
        })
      }
    })
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  // 删除图片
  deleteImg: function (e) {
    console.log("删除图片")
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs,
    countNum: that.data.max-imgs.length
      })
if(imgs.length<that.data.max){
      this.setData({
        isShowAdd: true
      })
    }
  },
})
        

 效果展示:

1 )图片未达上限

2 )图片已达到上限,隐藏添加按钮(ic_pic.png)

猜你喜欢

转载自www.cnblogs.com/hj0711/p/9262688.html