8

Assuming a server which cannot zip responses to user requests. A web developer nevertheless creates a myfile.txt.gz and stores it at http://www.mysite.com/myfile.txt.gz.

It is possible to have the browser automatically gunzip this compressed text file as part of the Ajax request and store the result in a var? If yes, how?

I am open to other compression algorithms if necessary.

Update

I am trying to use the following JQuery Ajax call:

var fetch = function() {

    $.ajax({
        type: 'GET',
        url:  "./data.txt.gz",
        headers: { "Accept-Encoding" : "gzip" },
        dataType: "text",
        async: true,
        success: function(result) {
            $("#midEnglob").text(result);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Issue: "
                + textStatus + " "
                + errorThrown + " !");
        }

    });

}

but I get the following in my browser:

enter image description here

Any ideas?

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • I'm not sure, but if you set the headers to `Content-type: text/plain` and `Content-encoding: gzip`, it might work. That's how HTML pages are sent gzipped. You should probably check the `Accept-Encoding` header first. – gen_Eric Feb 13 '13 at 16:50
  • I am trying but it does not seem to work. Do you have an operational code example? – Jérôme Verstrynge Feb 13 '13 at 17:52
  • All the code I suggested would be on the server-side. What server-side language (if any) are you using (I only know PHP)? You shouldn't have to do anything special in JavaScript, just do an AJAX call like you normally would. If the browser supports gzip, and the server sends the `Content-encoding` header, it'll automagically unzip it. – gen_Eric Feb 13 '13 at 18:01
  • Ok, the issue is that I don't control the server and can't guarantee the proper content-encoding header. Is there a way to tell Ajax the returned content is binary? – Jérôme Verstrynge Feb 13 '13 at 18:04
  • If you can't control the server side, then you may have to use a JavaScript implementation of gzip (Google around) to decode it. – gen_Eric Feb 13 '13 at 18:07
  • You can try to "steal" (LGPL) the (de)compressor from jsxgraph: https://github.com/jsxgraph/jsxgraph/blob/master/JSXCompressor/jsxcompressor.js Though the data may need to be base64 (which that file also contains an decoder/encoder) for it to work. – gen_Eric Feb 13 '13 at 18:17

1 Answers1

4

letting the browser uncompress it with Content-Encoding: gzip is probably the best. In case it doesn't work for your scenario, there are many LZW implementations in javascript like: https://gist.github.com/revolunet/843889

you might have to try out different implementations, i didn't check any of them myself.

Christian
  • 3,551
  • 1
  • 28
  • 24