整体逻辑如下:
element-upload上传图片压缩包 → 解压缩压缩包 → 获取压缩包的图片文件 → 将内存过大的图片进行压缩 → 将压缩之后的图片再次制作成压缩包 → 继续上传操作
先安装image-conversion, jszip模块,用于压缩和解压缩
upload部分
<el-upload
class="upload-demo"
ref="uploadNoMask"
:action="uploadUrl()"
:limit="1"
:show-file-list="true"
:before-upload="beforeAvatarUpload"
:on-success="handleSuccess"
:on-remove="handleRemove"
accept=".zip"
>
<div class="t_l">
<el-button size="small" type="primary">上传压缩包</el-button>
</div>
</el-upload>
引入模块
import * as imageConvsersion from 'image-conversion'
import JsZip from 'jszip'
beforeAvatarUpload方法
beforeAvatarUpload(file) {
const _this = this;
let zip = new JsZip(); //上传的压缩包
let nZip = new JsZip(); //新的压缩包
return new Promise((resolve) => {
let promise = [];
zip.loadAsync(file).then(res => {
res.forEach((relativePath, fil) => {
if(!fil.dir) {
let pro = _this.getBlob(zip,fil).then(data => {
nZip.file(fil.name, data, {binary: true});
}).catch(err => {
});
promise.push(pro);
}
});
Promise.all(promise).then(() => {
nZip.generateAsync({type: "blob"}).then(content => {
_this.$message.warning('正在压缩,请稍等~')
resolve(content);
})
})
})
})
},
getBlob(zip, fil) {
return new Promise((resolve, reject) => {
zip.file(fil.name).async("uint8array").then(u8 => {
let blob = new File([u8], fil.name.split("/")[1]);
if(blob.size > 409600) {
imageConvsersion.compressAccurately(blob, {
size: 400,
width: 400
}).then(res => {
resolve(res);
})
}else {
resolve(res);
}
})
})
},
功能完成。
网友评论