jquery 使用pako.js在javascript中使用Gzip字符串

7vux5j2d  于 2023-04-05  发布在  jQuery
关注(0)|答案(3)|浏览(200)

我读了一个关于使用pako.js在javascript中解压缩字符串的主题
ZLIB Decompression - Client Side
http://jsfiddle.net/9yH7M/1/
这是解压缩的代码

// Get some base64 encoded binary data from the server. Imagine we got this:
var b64Data     = 'H4sIAAAAAAAAAwXB2w0AEBAEwFbWl2Y0IW4jQmziPNo3k6TuGK0Tj/ESVRs6yzkuHRnGIqPB92qzhg8yp62UMAAAAA==';

// Decode base64 (convert ascii to binary)
var strData     = atob(b64Data);

// Convert binary string to character-number array
var charData    = strData.split('').map(function(x){return x.charCodeAt(0);});

// Turn number array into byte-array
var binData     = new Uint8Array(charData);

// Pako magic
var data        = pako.inflate(binData);

// Convert gunzipped byteArray back to ascii string:
var strData     = String.fromCharCode.apply(null, new Uint16Array(data));

// Output to console
console.log(strData);

我想一个方法来压缩字符串和输出可以解压缩上述代码
怎么能这样

xcitsw88

xcitsw881#

  • b64Data解压缩的代码可以简化为:
return pako.inflate(atob(b64Data), { to: 'string' });
  • 压缩为b64Data的代码:
return btoa(pako.deflate(stringToCompress, { to: 'string' }));
vltsax25

vltsax252#

您可以执行以下操作:

var binData = pako.deflate( "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
.map(function(x){return x.charCodeAt(0);}));

产量:
binData:Uint8阵列(37)[120,156,115,116,114,118,113,117,115,247,240,244,242,246,241,245,243,15,8,12,10,14,9,13,11,143,136,140,114,196,41,42,43,44,45,46,47,48,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,3、0、150、1、15、191]

var strData = String.fromCharCode.apply(null, pako.inflate(String.fromCharCode.apply(null, binData).split("").  map(function(x){return x.charCodeAt(0);})));

//yields back

"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"

bqjvbblv

bqjvbblv3#

在浪费了2个小时在不同的网站上尝试了20多个答案后,我想出了如何gzip和base64。它是如此简单:

var your_input_string = "hello hello hello!";
var compressed_uint8array = pako.gzip(your_input_string);
var b64encoded_string = btoa(String.fromCharCode.apply(null, compressed_uint8array));
console.log(b64encoded_string);

您需要包含pako.js。请参考此答案以了解如何获取它:How to use pako.js javascript? Pako is not defined

相关问题