Vant上传图片压缩
代码如下:
<van-uploader v-model="fileList" multiple :after-read="afterRead" max-count="1">
<button type="button"><span>+</span> 上传文件</button>
</van-uploader>
afterRead(file) {
if (!file.file) {
return;
}
// 此时可以自行将文件上传至服务器
file.status = "uploading";
file.message = "上传中...";
let maxSize = 1 * 1024 * 1024; //自己定义的文件大小,超过多少M就开始压缩(现在是1M)
let fileObj = file.file; // 当前的图片
if (fileObj.size > maxSize) {
this.imgcompress(fileObj, file);
} else {
const formData = new FormData();
formData.append("file[]", file.file); //此处的文件上传是formData格式
formData.append("private", 0);
let dirName = "voucher_img";
formData.append("dir", dirName);
console.log(file.file);
upload(formData)
.then((res) => {
this.rechargeFile = res.data.data;
file.status = "";
file.message = "";
})
.catch((err) => {
file.status = "failed";
file.message = "上传失败";
});
}
},
imgcompress(file, files) {
const img = document.createElement("img");
const reader = new FileReader(); // 读取文件资源实例
reader.readAsDataURL(file); //读取图片资源
reader.onload = (e) => {
//读取成功
img.src = e.target.result;
const { width: originWidth, height: originHeight } = img; //上传的图片的宽高
const maxWidth = 1000, //设置一个canvas 的最大宽高
maxHight = 1000;
if (originWidth > maxWidth || originHeight > maxHight) {
//计算出图片的缩放比例
if (originWidth > originHeight) {
//宽 大于 高
const Proportion = Math.ceil(originWidth / maxWidth);
let targetWidht = parseInt(originWidth / Proportion); //目标的宽度
let targetHeight = parseInt(originHeight / Proportion); //目标的高度
this.createCanvasCompress(targetWidht, targetHeight, img, files);
} else {
const Proportion = Math.ceil(originHeight / maxHight); //高大于宽
let targetWidht = parseInt(originWidth / Proportion); //目标的宽度
let targetHeight = parseInt(originHeight / Proportion); //目标的高度
let bold = this.createCanvasCompress(
targetWidht,
targetHeight,
img,
files
);
}
} else {
let quality = 0.8;
this.createCanvasCompress(
originWidth,
originHeight,
img,
files,
quality
);
}
};
},
createCanvasCompress(targetWidth, targetHeight, img, files, quality) {
let that = this;
return new Promise((resolve, reject) => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
// 设置宽高度为等同于要压缩图片的尺寸
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
//将img绘制到画布上
console.log(targetWidth, targetHeight);
context.drawImage(img, 0, 0, targetWidth, targetHeight);
files.content = canvas.toDataURL(files.file.type, 0.8); // 0.92为默认压缩质量
const newFile = this.dataURLtoFile(files.content, files.file.name);
const formData = new FormData();
formData.append("file[]", newFile);
formData.append("private", 0);
let dirName = "voucher_img";
formData.append("dir", dirName);
console.log(newFile);
upload(formData)
.then((res) => {
this.rechargeFile = res.data.data;
files.status = "";
files.message = "";
})
.catch((err) => {
files.status = "failed";
files.message = "上传失败";
});
});
},