在微信小程序里面,上传图片的时候,我使用的是wx.uploadFile ,所以它会有图片过大报错的问题,所以需要前端压缩后上传,虽然微信提供了自己的压缩api,但是很不好用,所以可以采用下面的方式来自己等比压缩。同时我还使用了Vant Weapp的Uploader来实现了图片的预览。
代码:
wxml:
<view style="padding: 0 16px" class="margin_top_normal">
<canvas style="width: {{cw}}px; height: {{ch}}px;position: absolute; z-index: -1; left: -10000rpx;; top: -10000rpx;" canvas-id="firstCanvas"></canvas>
<van-uploader file-list="{{ fileList }}" bind:after-read="uploadImg" max-count="4" data-number="0" alt="" bind:delete="deleteImg"/>
</view>
js:
//******************压缩图片*************************************//
uploadImg(e) {
let that = this;
let current = this;
console.log(e);
let index = e.currentTarget.dataset.number;
console.log(index);
let uploadFile = ''; // 最后处理完,图片上传的图片地址
console.log(e)
const tempFilePaths = e.detail.file.path;
// 获得原始图片大小
wx.getImageInfo({
src: tempFilePaths,
success(res) {
console.log('获得原始图片大小', res.width)
console.log(res.height)
var originWidth, originHeight;
originHeight = res.height;
originWidth = res.width;
console.log(originWidth);
// 压缩比例
// 最大尺寸限制
var maxWidth = 1100,
maxHeight = 500;
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight;
// 等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 要求宽度*(原生图片比例)=新图片尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// 更新 canvas 大小
that.setData({
cw: targetWidth,
ch: targetHeight
});
// 尝试压缩文件,创建 canvas
var ctx = wx.createCanvasContext('firstCanvas');
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(tempFilePaths, 0, 0, targetWidth, targetHeight);
ctx.draw(false, function () {
// 获得新图片输出
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: (res) => {
// 写入图片数组
var uploadpic = "uploadPic [" + index + "]";
//
that.setData({
[uploadpic]: res.tempFilePath
});
uploadFile = res.tempFilePath;
console.log("地址是:", uploadFile);
//把图片上传到远程服务器上
wx.uploadFile({
url: 'http://example.cn', // 远程服务器地址
filePath: uploadFile,
name: 'file',
formData: { parentPath: 'sign' },
success(res) {
// 上传完成需要更新
console.log("上传完成需要更新 ", res);
let jsondata = JSON.parse(res.data);
console.log("上传图片后:::::::", jsondata.data.url);
let imgs = current.data.fileList;
imgs.push({ url: jsondata.data.url })
current.setData({
fileList: imgs
})
},
});
},
fail: (err) => {
console.error(err)
}
}, this)
});
}
})
},
//******************压缩图片*************************************//