微信小程序多图片上传和预览

思路及代码

1.使用 chooseImage 获取到图片 并且在data中保存其生成的零时路径


Page({
  data: {
    imgs:[],
  },
  uploadImage(){
    let _this = this
      wx.chooseImage({
        count:3,
        success(res){
          _this.setData({imgs:res.tempFilePaths})
        }
      })
  },
})

2.在页面中 迭代这个数组 得到初步的预览效果

<image data-url="{{item}}"  wx:for="{{ imgs }}" wx:key="index" src="{{item}}" class="img1" />

3.通过微信自己的接口 previewImage 实现预览效果

<image bind:tap="yulan" data-url="{{item}}"  wx:for="{{ imgs }}" wx:key="index" src="{{item}}" class="img1" />
  yulan(e){
    let url = e.currentTarget.dataset.url
    let _this = this
    wx.previewImage({
      urls:_this.data.imgs,
      current:url,
      success(res){
        console.log(res)
      }
    })
  },

点击图片的预览效果

4.通过Promise多图上传服务器

<button class="btn1" bind:tap="tijiao">立即提交</button>
  tijiao(){
    new Promise(resolve => {
      let uploadImg = [];
      let _this = this
      this.data.imgs.some(item => {
        wx.uploadFile({
          url:'http://xxxxx',  //服务器地址
          filePath:item,name:'File',success(res){
          uploadImg.push(JSON.parse(res.data).data.File)
          uploadImg.length === _this.data.imgs.length?resolve(uploadImg):null
        }})
      })
    }).then(data => {

      })
    })
  },

迭代存放图片路径的数组(假设A),依次上传,每次上传成功后将 服务器返回的图片在服务器的路径 push到另一个(假设)B数组中,当B的长度和A相等时,所有图片上传完成,此时执行 Promise  resolve 判定,执行 then 之后的操作。

不知道 Promise 用法的,这边走 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值