Search code examples
javascriptzipjszip

Name .zip file created by JSZip


I am using JSZip and I am creating a .zip file with several .xml files inside it as shown below:

// get each xml in string format and add it to zip object
let zip = new JSZip();
for(let i = 0; i < containers.length; i++){
    let xml = getXML(i);
    zip.file("file"+i+".xml", xml);
}

// download the .zip file
zip.generateAsync({
    type: "base64"
}).then(function(content) {
    window.location.href = "data:application/zip;base64," + content;
});

The .zip file is created and downloaded perfectly but the name of the file is the default "download file". What i want to do is give a name to this file at will (for example allXMLs.zip).

I looked at the JSZip documentation but I did not find anything really enlightening, any help would be greatly appreciated.


Solution

  • You could create an anchor tag with a 'download' attribute that would allow you some control over the filename.

    zip.generateAsync({
        type: "base64"
    }).then(function(content) {
        var link = document.createElement('a');
        link.href = "data:application/zip;base64," + content;
        link.download = "your-file-name.zip";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });