微信小程序实现常用添加图片功能, 预览, 删除(完整版)超详细

我们先来看看效果图吧

我们来看看代码是怎么实现的

 wxml

<view class="img-li" wx:if="{{imgList.length<=5}}" bindtap="chooseSource">
          <image class="uploading-icon" src="../../../img/icon/icon-uploading-gray.png"></image>
        </view>

wxss

.img-li {
  width: 23%;
  height: 170rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}
.img-li:nth-child(4) {
  margin-right: 0;
}
.img-li:first-child {
  margin-right: none;
}
.img-li image {
  width: 100%;
  height: 100%;
}

js  最主要部分

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: []
  },
  // 点击添加选择
  chooseSource: function() {
    var _this = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择"],
      itemColor: "#CED63A",
      success: function(res) {
        if(!res.cancel) {
          if(res.tapIndex == 0) {
            _this.imgWShow("camera")        //拍照
          } else if (res.tapIndex == 1) {
            _this.imgWShow("album")      //相册
          }
        }
      }
    })
  },
  // 点击调用手机相册/拍照
  imgWShow: function(type) {
    var _this = this;
    let len = 0;
    if(_this.data.imgList != null) {
      len = _this.data.imgList.length
    }   //获取当前已有的图片
    wx.chooseImage({
      count: 6-len,     //最多还能上传的图片数,这里最多可以上传5张
      sizeType: ['original', 'compressed'],        //可以指定是原图还是压缩图,默认二者都有
      sourceType: [type],             //可以指定来源是相册还是相机, 默认二者都有
      success: function(res) {
        wx.showToast({
          title: '正在上传...',
          icon: "loading",
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表,tempFilePaths可以作为img标签的scr属性显示图片
        var imgList = res.tempFilePaths
        let tempFilePathsImg = _this.data.imgList
        // 获取当前已上传的图片的数组
        var tempFilePathsImgs = tempFilePathsImg.concat(imgList)
        _this.setData({
          imgList: tempFilePathsImgs
        })
      },
      fail: function () {
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
        return;
      }
    })
  },
  // 预览图片
  previewImg: function(e) {
    let index = e.target.dataset.index;
    let _this = this;
    wx.previewImage({
      current: _this.data.imgList[index],
      urls: _this.data.imgList
    })
  },
  // 点击删除
  deleteImg: function(e) {
    var _this = this;
    var imgList = _this.data.imgList;
    var index = e.currentTarget.dataset.index;      //获取当前点击图片下标
    wx.showModal({
      title: '提示',
      content: '确认要删除该图片吗?',
      success: function(res) {
        if(res.confirm) {
          console.log("点击确定了")
          imgList.splice(index, 1);
        } else if (res.cancel) {
          console.log("点击取消了");
          return false
        }
        _this.setData({
          imgList
        })
      }
    })
  },
})

这里我写了一个限制最多上传6张图片,可以看一下官方文档

发布了151 篇原创文章 · 获赞 28 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_42543264/article/details/105538890