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

思路及代码

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章