用Java缩小 - 用Javascript填充

时间:2013-06-27 10:27:13

标签: java javascript inflate deflate

我正在通过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));

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

我遇到了同样的问题。 js-deflate项目inflater看起来破碎了。我发现它可以在短输入上工作,但在长输入时失败(例如,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答案)。