Deflate in Java - Inflate in Javascript
Asked Answered
C

2

7

I'm sending compressed data from a java app via nodejs to a webpage. The data is compressed with the java deflater and base64 encoded. On the webpage I'm trying to inflate the data with https://github.com/dankogai/js-deflate, but it does not work (empty result). Am I missing something?

Java side:

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

var data = RawDeflate.inflate(Base64.fromBase64(compressed));
Cognition answered 27/6, 2013 at 10:27 Comment(0)
C
1

Try this:

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;
}
Copperas answered 3/7, 2013 at 11:4 Comment(1)
Works nicely in combination with JSInflateRudolph
G
0

I ran into the same problem. The js-deflate project inflater appears broken. I found it would work on a short input but fail on a long input (e.g., lorem ipsum as test data).

A better option turned out to be zlib.js.

Here is how I'm using it to inflate in Javascript a JSON object that is generated, compressed, and base64 encoded on the server:

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()));

(FYI, the helper functions are derived from other stackoverflow answers).

Galvanoscope answered 26/5, 2014 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.