简体   繁体   中英

Javascript string compression and PHP/Ruby decompression

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;

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

For example zip.js

Zip is of course also supported in PHP .

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM