编程语言
首页 > 编程语言> > wx小程序图片上传+预览+删除

wx小程序图片上传+预览+删除

作者:互联网

图片上传+预览+删除
<view class='uploader-list' wx:for="{{evidenceActList}}" wx:key="item.length">
    <view class='uploader-item-title'>{{index+1}}.{{item.name}}</view>
    <view class='upAdd' data-index="{{index}}" wx:if="{{item.flage}}">
        <image class='delete' data-index="{{index}}" src="{{imgUrl + '/images/icon_delete.png'}}" mode="widthFix" 
bindtap='deleteImg' data-type="evidenceActList"/> <image src='data:image/jpeg;base64, {{item.pics}}' bindtap='previewImg' data-type="evidenceActList"
data-index="{{index}}" mode="widthFix"/> </view> <view class='upAdd' bindtap='chooseImg' data-type="evidenceActList" data-index="{{index}}" wx:if="{{!item.flage}}"> <image src="{{imgUrl+'/images/icon_add.png'}}" data-index="{{index}}" mode="widthFix"/> </view> </view>
evidenceActList: [{
  name: '创业贷款申请书:',
  code: 1
},{
  name: '创业小额贷款担保推荐表:',
  code: 2
},{
  name: '织金县创业小额贷款担保审批表:',
  code: 3
},{
  name: '证明材料:',
  code: 4
}]
//上传图片开始
  chooseImg: function (e) {
    var that = this;
    var fileList = this.data.evidenceActList;
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    wx.chooseImage({
    // original 原图,compressed 压缩图,默认二者都有
      sizeType: ['original', 'compressed'], 
      // album 从相册选图,camera 使用相机,默认二者都有
      sourceType: ['album', 'camera'], 
      success: function (res) {
        // 返回选定照片的本地文件路径列表
        // tempFilePath可以作为img标签的src属性显示图片
        console.log('图片大小',res.tempFiles[0].size);
        var imgBase64 = wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], 'base64')
        fileList[index].pics = imgBase64
        fileList[index].flage = 1
        that.setData({
          evidenceActList: fileList,
        })
      },
    });
  },
  // 删除图片
  deleteImg: function (e) {
    var fileList = this.data.evidenceActList;
    var type = e.currentTarget.dataset.type;
    var that = this;
    var index = e.currentTarget.dataset.index;
    fileList[index].flage = 0
    that.setData({
      evidenceActList: fileList,
    })
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    //所有图片
    var fileList = this.data.evidenceActList;
    var pics = fileList[index].pics
    //声明文件系统
    const fs = wx.getFileSystemManager();
    //随机定义路径名称
    var times = new Date().getTime();
    var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: pics,
      encoding: 'base64',
      success: (res) => {
        //写入成功了的话,新的图片路径就能用了
        var urls = new Array(codeimg)
        wx.previewImage({
          //当前显示图片
          urls,
        })
      }
    });
  },

 

标签:index,预览,type,fileList,currentTarget,var,上传,evidenceActList,wx
来源: https://www.cnblogs.com/pleaseAnswer/p/14330830.html