Generating ZIP Files with Javascript
June 04, 2024I recently created a project called Hinge Trends and apart of the project was to take a set of in memory images, zip those images into a zip file then start a download all from inside the browser. The Library I used for creating the ZIP files is called JSZip and the documentation for how to extract a zip files is pretty good. However, the documentation on how to create a zip file is pretty bad and out of date.
So I thought I would write a quick article on how to generate a zip file (in memory) in the browser using javascript and trigger a download.
It is a pretty straight forward process. You need to create an instance of JSZip and hold your file contents as blobs. In my application I was pulling images so to get the blob form of images I ran a fetch command to download the images as blobs.
1async function GenerateZipDownload() {
2 const imageDownload = "https://unsplash.com/photos/two-people-in-scuba-gear-swimming-in-the-ocean-SuGTwrtPCg4";
3 const file = await fetch(imageDownload).then(r => r.blob());
4
5 const zip = new JSZip();
6 zip.file(`filename.jpg`, file); // adds the image file to the zip file
7}
You can run the `zip.file` command as many times as you need to add files to the outputted zip file. Just remember not to name files with conflicting names or they will be over written.
When you are ready to generate a zip file. You can generate the respective blob of the zip file with this command:
1const zipData = await zip.generateAsync({
2 type: "blob",
3 streamFiles: true
4 })
Then you can generate a link in-place and click it to trigger a download of the zip file:
1const link = document.createElement('a');
2 link.href = window.URL.createObjectURL(zipData);
3 link.download = `scuba-gear-swimming-data.zip`
4 link.click();
Ta'da! You now have a file generating and downloading in your browser. However to review I will leave the whole function here:
1async function GenerateZipDownload() {
2 const imageDownload = "https://unsplash.com/photos/two-people-in-scuba-gear-swimming-in-the-ocean-SuGTwrtPCg4";
3 const file = await fetch(imageDownload).then(r => r.blob());
4
5 const zip = new JSZip();
6 zip.file(`filename.jpg`, file); // adds the image file to the zip file
7
8 const zipData = await zip.generateAsync({
9 type: "blob",
10 streamFiles: true
11 })
12 const link = document.createElement('a');
13 link.href = window.URL.createObjectURL(zipData);
14 link.download = `scuba-gear-swimming-data.zip`
15 link.click();
16}