// 上传前
beforeUpload(file) {
// 创建一个Image对象
const image = new Image();
// 设置图片的src为选中文件的对象url
image.src = URL.createObjectURL(file);
return new Promise((resolve, reject) => {
image.onload = () => {
// 设置想要的图片宽度和高度
const width = 100;
const height = 200;
// 创建一个Canvas对象
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 设置Canvas的宽高
canvas.width = width;
canvas.height = height;
// 绘制图片
ctx.drawImage(image, 0, 0, width, height);
// 将Canvas转换为blob数据
canvas.toBlob(blob => {
if (blob) {
// 使用新的blob对象替换原有的文件对象
file = new File([blob], file.name, {
type: 'image/png',
});
// 继续上传流程
resolve(file);
} else {
reject(new Error('Canvas conversion error'));
}
}, 'image/png');
};
image.onerror = reject;
});
},