微信小程序之批量上传并压缩图片的实例代码

具体内容如下所示:

首先,要在.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,
    })
   }
  })
 },

以上所述是小编给大家介绍的微信小程序之批量上传并压缩图片的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容