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

时间:2021-09-02 20:00:10

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发送回服务器。为了限制交通,我想对他们进行压缩。这在Javascript中可能吗?如何从JSON的字符串表示中创建字节数组?谢谢。

3 个解决方案

#1


6  

A new solution to zip data is now available: jszip.

zip数据的新解决方案现在可用:jszip。

#2


3  

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-encode:

// 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("");
}

#3


0  

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

我相信,这是一篇关于这个主题的*文章http://en.wikipedia.org/wiki/http_压缩

#1


6  

A new solution to zip data is now available: jszip.

zip数据的新解决方案现在可用:jszip。

#2


3  

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-encode:

// 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("");
}

#3


0  

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

我相信,这是一篇关于这个主题的*文章http://en.wikipedia.org/wiki/http_压缩