5

Is there a Javascript compression and PHP/Ruby decompression library for strings? I need it because I need to send a very long text string using Ajax on a slow upload link to a web server which uses PHP/Ruby as server-side language.

var x = $('#sources').html();
// a very-very long text
var xo = x, o = {};
if(x.length>512*1024) {
  x = compress(x);
  o.c = 1;
}
o.x = x;
$.post('target.php',o,function(res){alert(res==xo)});

On server side (for example, PHP):

<?php
  if(isset($_POST['c']) && $_POST['c']=='1') {
    $x = decompress($_POST['x']);
  } else {
    $x = $_POST['x'];
  }
  echo $x;
Kokizzu
  • 24,974
  • 37
  • 137
  • 233

4 Answers4

4

There are many JS implementations of the most common compression algorithm, Zip.

For example zip.js

Zip is of course also supported in PHP.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

That should do it

http://webdevwonders.com/lzw-compression-and-decompression-with-javascript-and-php/

LZW is good for strings that actually contain human readable text

naugtur
  • 16,827
  • 5
  • 70
  • 113
0

Assuming that you send your files over http, I would suggest that you let your web server handle this by sending file with gzip content-encoding.

If for example you use Apache, you can enable mod_deflate

If for some reason you can't change your web server configuration, php also has a built-in gzip handler you could use instead. See: ob_gzhandler

Edit:

As for client to server, it doesn't look like this is directly supported by any XmlHttpRequest implementations. You could perhaps find a custom gzip compression algorithm for Javascript and then set the request-header to indicate that it's compressed .That way it becomes transparently decoded by the web server and you don't have to do anything special in php.

See this page: JavaScript implementation of Gzip.

Community
  • 1
  • 1
troelskn
  • 115,121
  • 27
  • 131
  • 155
  • 1
    You can compress answers from the server to the client but can you compress requests too ? – Denys Séguret Feb 14 '13 at 08:17
  • Good point .. Doesn't look like any XmlHttpRequest implementations supports this. – troelskn Feb 14 '13 at 08:27
  • I think a problem is that the client doesn't know what compression schemes are handled by the server. This might need a first request just to ask this and so could be painful to handle in javascript. – Denys Séguret Feb 14 '13 at 08:29
  • In theory yes, but since OP knows which server the client is talking to, it is in fact known. – troelskn Feb 14 '13 at 08:30
0

Running a google search for "ruby decompress string" comes up with this: How to decompress Gzip string in ruby? which is what you're looking for.

Community
  • 1
  • 1
Allen
  • 794
  • 1
  • 6
  • 19