// js压缩图片方法
const compressImage = (file, maxWidth, maxHeight, callback)=> {
// 设置为异步同步,保证处理完成后,拿到返回值再进行上传
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function () {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height = maxWidth / width * height;
width = maxWidth;
}
if (height > maxHeight) {
width = maxHeight / height * width;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function(blob) {
//blob转file文件
var newfile = new File([blob], 'test.jpg', { type: blob.type })
callback(newfile);
//异步处理完成
resolve('value')
}, file.type);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
})
}
//使用===拿到file文件后调用
console.log('上传的文件')
console.log(file)
// js压缩图片
//配置参数,款和高只会取一个值
const maxWidth = 400;
const maxHeight = 400;
var newfile = ''
// 设置为异步同步,保证处理完成后,拿到返回值再进行上传
//注意async和await的使用!你的方法需要加async
await compressImage(file, maxWidth, maxHeight,function(file){
console.log(file)
newfile = file
})
//走你的上传图片方法
const formData = new FormData()
formData.append('myfile',newfile)
formData.append('packageName','pc')
11-21
11-14
230
01-21
07-25
502