微信小程序之批量上传并压缩图片

就不说网上那些不负责任的到处抄还存在缺陷的做法了,直接上代码吧。

具体如下(有更好的建议的大牛欢迎评论留下您宝贵的意见与指导):

首先,要在.wxml文件里面创建一个canvas,作用是承载压缩的图片,以供上传的时候获取

这个canvas不能隐藏,否则没效果,可以将其移至屏幕外。

<canvas canvas-id='attendCanvasId' class='myCanvas'></canvas>


然后呢,就是.js文件里面的方法了

// 点击加_压缩
  takePhoto: function () {
    var that = this;
    let imgViewList = that.data.imgViewList; //这个是用来承载页面循环展示图片的
      //拍照、从相册选择上传
      wx.chooseImage({
        count: 4,    //这个是上传的最大数量,默认为9
        sizeType: ['compressed'],    //这个可以理解为上传的图片质量类型(官方给的),虽然没什么卵用,要不然还要我们自己写压缩做什么
        sourceType: ['album', 'camera'],    //这个是图片来源,相册或者相机
        success: function (res) {
          var tempFilePaths = res.tempFilePaths    //这个是选择后返回的图片列表
          that.getCanvasImg(0, 0, tempFilePaths);    //进行压缩
        } 
      });
  },
  //压缩并获取图片,这里用了递归的方法来解决canvas的draw方法延时的问题
  getCanvasImg: function (index,failNum, tempFilePaths){
    var that = this;
    if (index < tempFilePaths.length){
      const ctx = wx.createCanvasContext('attendCanvasId');
      ctx.drawImage(tempFilePaths[index], 0, 0, 300, 150);
      ctx.draw(true, function () {
        index = index + 1;//上传成功的数量,上传成功则加1
        wx.canvasToTempFilePath({
          canvasId: 'attendCanvasId',
          success: function success(res) {
            that.uploadCanvasImg(res.tempFilePath);
            that.getCanvasImg(index,failNum,tempFilePaths);
          }, fail: function (e) {
            failNum += 1;//失败数量,可以用来提示用户
            that.getCanvasImg(inedx,failNum,tempFilePaths);
          }
        });
      });
    }
  },
  //上传图片
  uploadCanvasImg: function (canvasImg){
    var that = this;
    let imgViewList = that.data.imgViewList;
    var tempImg = canvasImg;
    wx.uploadFile({
      url: app.d.fileServer,//文件服务器的地址
      filePath: tempImg,
      formData: {
        paramPath: "gift"
      },
      name: 'file',
      success: function (res) {
        var json2map = JSON.parse(res.data);
        imgViewList.push(app.d.imageUrlFix + json2map[0].fileUrl);
        that.setData({
          imgViewList: imgViewList,
        })
      }
    })
  },

以上就是我自己的处理方法,希望能够给大家一点帮助吧,最起码比那些到处乱抄还一堆问题的要好很多。

欢迎大家留言评论~~~

发布了14 篇原创文章 · 获赞 23 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Jaiaxn/article/details/80902029