本文主要是介绍Vue中项目进行文件压缩与解压缩 (接口返回文件的url压缩包前端解析并展示出来,保存的时候在压缩后放到接口入参进行保存),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装 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.tableSsjsonUrlfetch(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 {// designInfoUpdateconst res = await updateTableFileGzip(formData);if (res.code === 0) {this.$modal.msgSuccess('保存成功!')} else {// this.$modal.msgError15('保存失败!')}} catch (error) {// this.$modal.msgError15('保存失败!')}
参考链接 Vue中如何进行文件压缩与解压缩?_vue压缩文件_毕设徐师兄的博客-CSDN博客
这篇关于Vue中项目进行文件压缩与解压缩 (接口返回文件的url压缩包前端解析并展示出来,保存的时候在压缩后放到接口入参进行保存)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!