iView,Upload组件beforeUpload压缩图片
文章目录
关键代码
<Upload
multiple
:format="['jpg','jpeg','png']"
:beforeUpload="beforeUpload"
action=""
:on-success="upload"
>
<Button icon="ios-cloud-upload-outline">上传图片</Button>
</Upload>
import Compressor from "compressorjs"
beforeUpload(file) {
return new Promise((resolve, reject) => {
let isLt1M = file.size / 1024 / 1024 < 1;
if (isLt1M) {
resolve(file);
}
new Compressor(file, {
quality: 0.3,
success(res) {
res = new File([res], res.name, {
type: res.type,
lastModified: Date.now()
});
resolve(res);
},
error(err) {
reject()
}
});
});
}
代码解释
图片压缩工具用的是 compressorjs,由于compressorjs压缩图片后返回的是Blob对象,而iView只有当beforeUpload方法返回File对象时,才会将压缩后的文件替换用户上传的原文件,所以压缩后需要将Blob对象转换为File对象。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论