前端使用pako对json串进行压缩,转成base64并且解压缩的过程
1 export function compressAndb64encode(originalData) { 2 // 将字符串转换为字节序列 3 const binaryString = encodeURIComponent(originalData) 4 const charList = binaryString.split('') 5 const binaryArray = charList.map(char => char.charCodeAt(0)) 6 // 压缩数据 7 const compressed = pako.deflate(new Uint8Array(binaryArray)) 8 9 //解决图片过多即数据量过大时,会出现内存溢出的问题 10 const CHUNK_SIZE = 0x8000 11 let index = 0 12 const length = compressed.length 13 let result = '' 14 let slice = '' 15 while (index < length) { 16 slice = compressed.subarray(index, Math.min(index + CHUNK_SIZE, length)) 17 result += String.fromCharCode.apply(null, slice) 18 index += CHUNK_SIZE 19 } 20 let compressedData = btoa(result) 21 22 //let compressedData = btoa(String.fromCharCode.apply(null, compressed)) // 23 return compressedData 24 25 /* const myUint8Array = pako.deflate(originalData, { to: 'string' }) 26 const binary = myUint8Array.join(',') 27 const compressedData = btoa(binary) 28 return compressedData */ 29 } 30 export function deCompressAndb64decode(compressedData) { 31 // 解压数据 32 const compressedBinary = atob(compressedData) 33 const compressedArray = compressedBinary 34 .split('') 35 .map(char => char.charCodeAt(0)) 36 37 const decompressed = pako.inflate(new Uint8Array(compressedArray)) 38 const decompressedString = Array.from(decompressed) 39 .map(charCode => String.fromCharCode(charCode)) 40 .join('') 41 42 let originalData = decodeURIComponent(decompressedString) 43 return originalData 44 45 /* const binary = atob(compressedData) 46 const myUint8Array = new Uint8Array(binary.split(',')) 47 const decompressed = pako.inflate(myUint8Array, { to: 'string' }) 48 return decompressed */ 49 }
尤其要注意中间解决内存溢出的问题,搜索了有一阵时间才解决,以此记录下来,方便下次直接使用!!!