AJAX response gives a corrupted compressed (.tgz) file AJAX response gives a corrupted compressed (.tgz) file ajax ajax

AJAX response gives a corrupted compressed (.tgz) file


I don't know if this thread will be helpful for somebody, but just in case I figured out the cause and a possible solution for my problem.

The cause

Default Javascript variables store information in Unicode/ASCII format; they are not prepared for storing binary data correctly and this is why one can easily see wrong characters interpreted (this also explains why repetitions of EF, BF, etc. were observed in the Hex Viewer, which stand for wrong characters of ASCII/Unicode).

The solution

The last browser versions implement the so called typed arrays. They are javascript arrays that can store data in different formats (also binary). Then, if one specifies that the XMLHttpRequest response is in binary format, data will be correctly stored and, when blobed into a file, the file will not be corrupted. Check out the code I used:

var xhr = new XMLHttpRequest();xhr.open('POST', url, true);xhr.responseType = 'arraybuffer';

Notice that the key point is to define the responseType as "arraybuffer". It may be also interesting noticing that I decided not to use Jquery for the AJAX anymore. It poorly implements this feature and all attempts I did to parse Jquery were in vain (overrideMimeType described somewhere else didn't work in my case). Instead, old plain XMLHttRquest worked pretty nicely.