1、安装模块 image-conversion
npm install --save image-conversion
2、在utils/utils文件封装全局方法
import * as imageConversion from 'image-conversion'; /** * 压缩图片 * inputFile :file * toSize : 想要压缩的大小 * */ export async function compressAccurately(inputFile, toSize) { const resAvatarBlob = await imageConversion.compressAccurately(inputFile, toSize); const resAvatarFile = new window.File( [resAvatarBlob], inputFile.name, { type: inputFile.type }, ); resAvatarFile.uid = inputFile.uid return resAvatarFile; }
3、将方法绑定到全局/main.js
import * as utils from '@/utils/utils' Vue.prototype.utils = utils;
4、使用
/** 图片上传之前的校验 */ async beforeImgUpload(file) { // const resAvatarBlob = await imageConversion.compressAccurately(file, 400); // let resAvatarFile = new window.File( // [resAvatarBlob], // file.name, // { type: file.type }, // ); // // resAvatarFile.uid = file.uid // return resAvatarFile; return this.utils.compressAccurately(file,600) },