判断逻辑 大于200KB 压缩上传,否则不做处理上传原始图片
1.安装插件
yarn add image-conversion
2.引入
import { compressAccurately} from 'image-conversion'
3.修改beforeUpload函数
beforeUpload: function(file){
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt200K = file.size / 1024 < 200;
if (!isJpgOrPng) {
this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
return false;
}
if (isLt200K) {
//小于200K不做处理
return true;
}
return new Promise((resolve) => {
// 压缩到200KB,这里的200就是要压缩的大小,可自定义
// compressAccurately(file, 200).then(res => {
// console.log(res)
// resolve(res);
// });
//compressAccurately有多个参数时传入对象
compressAccurately(file, {
size: 2048, //图片大小压缩到200kb
width:400 //宽度压缩到1280
}).then(res => {
//保留原始文件名
let files = new File([res], file.name, { type: file.type });
resolve(files)
})
})
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)