微信小程序选择图片,上传图片,删除图片功能

753 阅读1分钟
  • html
 
<view class="choose">
     <view class="content">
       <image class="add" bindtap="upload" src="../../images/icon/add.png"></image>
     </view>
     <view class="content2" wx:for="{{worksImgs}}" wx:key="*this">
       <image class="add" src="{{item}}"></image>
       <image class="delete" bindtap="delete" bindtap='clearImg' data-index='{{index}}' src="../../images/icon/cacle.png"></image>
     </view>
   </view>

  • css
.choose{
 display: flex;
 flex-flow: wrap;
 background: white;
 padding: 0 30rpx;
}
.content{
padding: 20rpx 0rpx;
width: 33%;
text-align: center;
height: 150rpx;
}
.add{
 width:150rpx;
height:150rpx;
}
.content2{
 padding: 20rpx 0rpx;
width: 33%;
text-align: center;
position: relative;
height: 150rpx;
}
.delete{
 width: 40rpx;
 height: 40rpx;
 position: absolute;
 left: 144rpx;
 top: 21rpx;
}
  • js
 data:{
      chooseImg: [],
     worksImgs: [],
   }
 // 上传图片
 upload() {
   console.log('worksImgs', this.data.worksImgs.length);
   let that = this
   let a = that.data.worksImgs.length
   let len = 0;
   if (that.data.chooseImg != null) {
     len = that.data.chooseImg.length;
   } //获取当前已有的图片
   let b = 5 - Number(a);
   if (b <= 0) {
     wx.showToast({
       title: '最多只能上传5张图片',
       icon: 'none',
     })
     return false
   } else {
     wx.chooseImage({
       count: b, //最多选择2张图片- that.data.banner.length,
       sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
       sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
       success: function (res) {
         let choose = res.tempFilePaths
         let tempFilePathsimg = that.data.chooseImg //获取当前已上传的图片的数组
         // console.log(choose)
         for (let i = 0; i < res.tempFilePaths.length; i++) {
           wx.uploadFile({
             url: 'http://47.112.223.0:8081/imgUpload/one',
             method: 'POST',
             filePath: res.tempFilePaths[i],
             name: 'file',
             header: {
               'content-type': 'application/json',
             },
             success(res) {
               let data = JSON.parse(res.data);
               console.log(data)
               let wark = that.data.worksImgs
               wark.push(data.result)
               console.log(wark)
               that.setData({
                 worksImgs: wark
               })
             },
             fail(res) {
               console.log(res)
             }
           })
           // }
         }
       },
     })
   }
 },
删除选中图片
// 删除照片
 clearImg(e) {
   let index = e.currentTarget.dataset.index;
   this.data.worksImgs.splice(index, 1);
   this.setData({
     worksImgs: this.data.worksImgs
   })
   console.log(this.data.worksImgs)
 },