I want to download gzipped csv files from a web server and ungzip then in the browser.
So far I have tried using pako
and zlib
to take a file gzipped on my server, but have had various issues. Trying to unzip a unix-gzipped file, I kept getting an incorrect header message.
Next, I tried using node to zip the file on the server, and am currently getting this error
Uncaught Error: invalid file signature:,�
Here is the command I am using to get the file:
$.ajax({ type: "GET", url: 'public/pols_zlib.csv.gz'})
.done(function(d){
var gunzip = new Zlib.Gunzip(d);
plain = gunzip.decompress();
});
I am looking for any way to zip a file on my server and unzip it in the browser.
Another answer for a pure binary solution that requires the browser to support typedarrays. With this method, there is no need to use base64 encoding, thus allowing for smaller file size. This solution is recommended when older browser support is not a requirement.
Download and add a reference to pako_inflate.min.js.
Here is the HTML that I have tested.
<html>
<head>
<title>Binary Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="~/Scripts/pako_inflate.min.js" type="text/javascript"></script>
<script type="text/javascript">
var oReq = new XMLHttpRequest();
oReq.open("GET", 'file.csv.gz?_=' + new Date().getTime(), true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
var data = pako.inflate(byteArray);
//$('body').append(String.fromCharCode.apply(null, new Uint16Array(data))); // debug
$('#link').attr("href", "data:text/csv;base64," + btoa(String.fromCharCode.apply(null, new Uint16Array(data))));
}
};
oReq.send(null);
</script>
</head>
<body>
<a id="link" download="file.csv">file</a>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With