安装 npm install pako
在Vue组件中引入pako:
import pako from 'pako';
接口返回的url是这个字段 tableSsjsonUrl 其实打开就是压缩包
const source = await tableFileUrl ({ id: this.$route.query.id});
if(source.code === 0) {
this.titleName = source.data.tableName
}
if(source.code === 0 && source.data.tableSsjsonUrl) {
const fileUrl = source.data.tableSsjsonUrl
fetch(fileUrl, {
headers: {
'Cache-Control': 'no-cache'
}
})
.then(response => response.blob())
.then(blob => {
const reader = new FileReader();
reader.onload = () => {
const compressedData = new Uint8Array(reader.result);
const decompressedData = pako.ungzip(compressedData, { to: 'string' });
this.spread.fromJSON(JSON.parse(decompressedData));
};
reader.readAsArrayBuffer(blob);
})
.catch(error => {
console.error('Failed to fetch file:', error);
});
}
压缩传参如下
let spreadJSON = JSON.stringify(this.spread.toJSON({ }));
const uint8Array = new TextEncoder().encode(spreadJSON);
// 进行gzip压缩
const compressedData = pako.gzip(uint8Array);
// 将压缩后的数据转换成Blob类型并下载
// const blob = new Blob([compressedData], { type: 'application/gzip' });
// saveAs(blob, 'example.gz');
// 创建FormData对象
const formData = new FormData();
// 将压缩后的数据作为FormData的一部分
formData.append('file', new Blob([compressedData]));
formData.append('id', this.$route.query.id);
console.log(formData.get('file'), '9999999999')
try {
// designInfoUpdate
const res = await updateTableFileGzip(formData);
if (res.code === 0) {
this.$modal.msgSuccess('保存成功!')
} else {
// this.$modal.msgError15('保存失败!')
}
} catch (error) {
// this.$modal.msgError15('保存失败!')
}
Vue中项目进行文件压缩与解压缩 (接口返回文件的url压缩包前端解析并展示出来,保存的时候在压缩后放到接口入参进行保存)
于 2023-11-24 09:29:35 首次发布