7

我正在通过 nodejs 从 java 应用程序将压缩数据发送到网页。数据使用 java deflater 压缩和 base64 编码。在网页上,我试图用https://github.com/dankogai/js-deflate来膨胀数据,但它不起作用(空结果)。我错过了什么吗?

Java端:

private String compress(String s) {
    DeflaterOutputStream def = null;
    String compressed = null;
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // create deflater without header
        def = new DeflaterOutputStream(out, new Deflater(Deflater.DEFAULT_COMPRESSION, true));
        def.write(s.getBytes());
        def.close();
        compressed = Base64.encodeBase64String(out.toByteArray());
        System.out.println(compressed);
    } catch(Exception e) {
        Log.c(TAG, "could not compress data: " + e);
    }
    return compressed;
}

Javascript方面:

var data = RawDeflate.inflate(Base64.fromBase64(compressed));
4

2 回答 2

1

尝试这个:

public static String compressAndEncodeString(String str) {
    DeflaterOutputStream def = null;
    String compressed = null;
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // create deflater without header
        def = new DeflaterOutputStream(out, new Deflater(Deflater.BEST_COMPRESSION, true));
        def.write(str.getBytes());
        def.close();
        compressed = Base64.encodeToString(out.toByteArray(), Base64.DEFAULT);
    } catch(Exception e) {
        Log.e(TAG, "could not compress data: " + e);
    }
    return compressed;
}
于 2013-07-03T11:04:56.980 回答
0

我遇到了同样的问题。js-deflate 项目充气器出现损坏。我发现它可以在短输入上工作,但在长输入上会失败(例如,lorem ipsum 作为测试数据)。

一个更好的选择原来是zlib.js

以下是我如何使用它在 Javascript 中扩展在服务器上生成、压缩和 base64 编码的 JSON 对象:

var base64toBinary = function (base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        var ascii = binary_string.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes.buffer;
}

var utf8ToString = function (uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
       decodedString = decodeURIComponent(escape(encodedString));
    return decodedString;
}

var object = JSON.parse(utf8ToString(
  new Zlib.RawInflate(base64toBinary(base64StringFromServer)).decompress()));

(仅供参考,辅助函数源自其他 stackoverflow 答案)。

于 2014-05-26T20:49:57.613 回答