Search code examples
javascriptexcelzipjszip

zip excel files from the server for download


I'm trying to use jszip.js to bundle multiple excel files from the server which should be downloaded together as a zip file on click.

When I just try to replace the demo script, I can create a zip file, but it is empty.

When I put two files in the zip.file, than the first one appears in the zip, but it is corrupted. Like:

var zip = new JSZip();
zip.file('http://website/file1.xlsx', 'http://website/file2.xlsx');
var content = zip.generate({type:"blob"});
saveAs(content, "example.zip");

So I should put the name of the file on the first position and than the location of the file, but than I have to access it on an other way...

I think I just don't check how the API works.

It would be great to get an example with at least two files which are hosted on a server...


Solution

  • JSZip can't download content but you can use a XHR (with xhr.responseType = "arraybuffer") or JSZipUtils if you need to support IE <= 9. You can find more details on this page of the documentation.

    What you try to do looks like this example: download several files and zip them.

    Without copy/pasting the whole code, the example:

    • triggers ajax calls (with JSZipUtils but you can easily only use a responseType = "arraybuffer" if you only supports recent browsers)
    • wrap them into promises (jQuery promises here but you can use your own)
    • add the result into a zip object
    • wait for all promises to complete before triggering a download