// 点击加_压缩 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, }) } }) },