1,下载插件依赖
npm i image-conversion -S
2,封装一个图片压缩组件
新建一个js文件命名随便,在文件中引入依赖:import * as imageConversion from 'image-conversion',写一个方法暴露出去。
compressImg.js
import * as imageConversion from 'image-conversion'
export function compressImg(file){
return new Promise((resolve, reject) => {
const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/png';
let isLt2M = file.size / 1024 / 1024 < 2 // 判定图片大小是否小于4MB
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG png jpeg格式!');
}
if (isLt2M) {
resolve(file)
}else if(!isLt2M){
imageConversion.compressAccurately(file, 400).then(res => {
resolve(res)
console.log(res);
}).catch(() => {
this.$message.error('图片压缩失败,请联系管理员进行查看!')
reject()
})
}
})
}
3,图片上传文件
图片上传文件引入封装好的组件
beforeAvatarUpload(file) {
return compressImg(file)
},