您的位置:首页 > 移动开发 > 微信开发

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

2018-07-05 14:18 846 查看

具体内容如下所示:

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

总结

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息