如何在发送到服务器之前在 javascript 中压缩/gzip 用户数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8102824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:17:44  来源:igfitidea点击:

How to zip/gzip user data in javascript before sending to the server?

javascriptajaxjsongzip

提问by Jér?me Verstrynge

I am still new to Javascript. I have a situation where many users can send large JSON back to the server. In order to limit traffic, I would like to gzip them. Is this possible in Javascript? How can I can create a byte array from the string representation of the JSON? Thanks.

我还是 Javascript 的新手。我有一种情况,许多用户可以将大型 JSON 发送回服务器。为了限制流量,我想对它们进行gzip。这在 Javascript 中可能吗?如何从 JSON 的字符串表示创建字节数组?谢谢。

回答by Jason T Featheringham

I know of no gzip implementations, but there are other compression methods at your disposal.

我知道没有 gzip 实现,但是您可以使用其他压缩方法。

This will lzw-encode a string using JavaScript:

这将使用 JavaScript 对字符串进行 lzw 编码:

// lzw-encode a string
function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict[phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            dict[phrase + currChar] = code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
}

回答by Tom

I believe so, here's a wikipedia article on the subject http://en.wikipedia.org/wiki/HTTP_compression

我相信是这样,这里有一篇关于这个主题的维基百科文章http://en.wikipedia.org/wiki/HTTP_compression