Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download multiple files then compress to one zip file using JSZip & JSZip-utils
var zip = new JSZip();
var count = 0;
var zipFilename = "zipFilename.zip";
var urls = [
'http://image-url-1',
'http://image-url-2',
'http://image-url-3'
];
urls.forEach(function(url){
var filename = "filename";
// loading a file and add it in a zip file
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
throw err; // or handle the error
}
zip.file(filename, data, {binary:true});
count++;
if (count == urls.length) {
var zipFile = zip.generate({type: "blob"});
saveAs(zipFile, zipFilename);
}
});
});
@cunneen

This comment has been minimized.

Copy link

@cunneen cunneen commented Jul 31, 2016

Thanks.

@evanalmighty

This comment has been minimized.

Copy link

@evanalmighty evanalmighty commented Aug 16, 2016

How would you go about doing this in version 3?

@arinaldi

This comment has been minimized.

Copy link

@arinaldi arinaldi commented Nov 7, 2016

I got this working in version 3 by changing the IF statement:

if (count == urls.length) {
   zip.generateAsync({type:'blob'}).then(function(content) {
      saveAs(content, zipFilename);
   });
}
@ramuchintha

This comment has been minimized.

Copy link

@ramuchintha ramuchintha commented Dec 12, 2016

Hi,

I tried with the above script, every thing went fine, it is zipping the three files in to one zip. But i can see the last file content is adding to the zip three times.Means when the download the zip file i can see the same "http://image-url-3" three times inside the zip, instead of "http://image-url-1", http://image-url-2, http://image-url-3

Can you please help me to resolve this issue?

@ramuchintha

This comment has been minimized.

Copy link

@ramuchintha ramuchintha commented Dec 12, 2016

Hi noelvo,

I tried the above script but i'm getting the same file content for both files, i mean when i tried to zip the two files from server, it is zipping two files but i'm getting the same content in both the files . Below is my code.

var zip = new JSZip();
var count = 0;

for(var url=0;url<msmSystemDownloadUrls.length;url++)
{
var filename = ccmFileNames[url];
console.log(msmSystemDownloadUrls[url]);
JSZipUtils.getBinaryContent(msmSystemDownloadUrls[url], function (err, data) {
if(err) {
throw err; // or handle the error
}
//zip.file(filename, data, {binary:true});
for(var fl=0;fl<ccmFileNames.length;fl++){
zip.file(ccmFileNames[fl], data, {binary:true});
}

 count++;
 if (count == msmSystemDownloadUrls.length) {
   zip.generateAsync({type:'blob'}).then(function(content) {
	  saveAs(content, "ramaSystemReport.mrep");
	  msmSystemDownloadUrls = [];
	  ccmFileNames= [];
   });
 }

});
}

I'm calling this function by using ajax .

Can you please help me to resolve this issue ASAP?

Waiting for your kind reply.

@lmartinez99

This comment has been minimized.

Copy link

@lmartinez99 lmartinez99 commented May 5, 2017

version 3
http://github.com/Stuk/jszip/zipball/master
https://stuk.github.io/jszip/
https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js

<script type="text/javascript" src="js/FileSaver.min.js"></script>
<script src="js/jszip.min.js" type="text/javascript">  </script>

var urls = [
                 "images/20170420_145140.jpg", 
                 "images/20170503_142841.jpg", 
                 "images/20170503_084035.jpg", 
                 "images/20170503_163354.jpg", 
                 "images/20170503_163334.jpg", 
                 "images/20170421_114806.jpg"];
var nombre = "Zip_img";
//The function is called
compressed_img(urls,nombre);

function compressed_img(urls,nombre) {
  var zip = new JSZip();
  var count = 0;
  var name = nombre+".zip";
  urls.forEach(function(url){
    JSZipUtils.getBinaryContent(url, function (err, data) {
      if(err) {
         throw err; 
      }
       zip.file(url, data,  {binary:true});
       count++;
       if (count == urls.length) {
         zip.generateAsync({type:'blob'}).then(function(content) {
            saveAs(content, name);
         });
       }
      });
  });
}
@RAJASRINU

This comment has been minimized.

Copy link

@RAJASRINU RAJASRINU commented Jun 12, 2017

Hi Ramuchnadra,

You can handle the incremental zip file generation with below changes

var zip = new JSZip();
var count = 0;
var count1 =0;
var zipFilename = "zipFilename.zip";
var urls = [
'http://image-url-1',
'http://image-url-2',
'http://image-url-3'
];

urls.forEach(function(url){
var filename = "filename";
// loading a file and add it in a zip file
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
throw err; // or handle the error
}
zip.file(filename, data, {binary:true});
count++;
if (count == urls.length) {
zip.generateAsync({type:'blob'}).then(function(content) {
**count1++;

  if(count1 == urls.length)**

saveAs(content, zipFilename);
});
}
});
});

Thanks & Regards,
V Rajesh
9884468991

@srinivasulu538034

This comment has been minimized.

Copy link

@srinivasulu538034 srinivasulu538034 commented Jun 21, 2017

Using Angular 2 :


  1. I have installed the jzip-utils using the npm command
    npm install jszip-utils
  2. When trying to include the reference in ***.ts file, i am getting a message Cannot find module 'jszip-utils'
  3. When observed the folder "node_modules", new folder 'jszip-utils' created with the required files

Any guidance will be great helpful.

Regards,
Srinivas

@kinjalhinguss

This comment has been minimized.

Copy link

@kinjalhinguss kinjalhinguss commented Oct 29, 2018

Doesn't work with firefox 63.
File is downloaded, but it's file type is 'File'. and i cannot open it.

Please guide me on this.

Regards,
Kinjal

@gurrrung

This comment has been minimized.

Copy link

@gurrrung gurrrung commented Dec 29, 2018

don't forget to make the filename vary with each iteration using index and add the extension . for example i added .jpg for images. :)

@Anu1601CS

This comment has been minimized.

Copy link

@Anu1601CS Anu1601CS commented Dec 31, 2018

Axios Version

      Your file object
       const payload = {};		
        var zip = new jsZip();
	var count = 0;
	payload.forEach((file) => {
		axios
			.get(file.filePath, {
				responseType: 'blob'
			}, )
			.then((response) => {

				zip.file(file.name, response.data, {
					binary: true
				});

				++count;

				if (count == payload.length) {

					zip.generateAsync({
						type: 'blob'
					}).then(function (content) {
						FileSaver.saveAs(content, new Date + '.zip');
					});
				}

			})
			.catch((error) => {
				console.log(error);
			});
@karnadii

This comment has been minimized.

Copy link

@karnadii karnadii commented Apr 13, 2019

got it working, thanks to Anu1601CS

downloadChapter() {
      var zip = new JSZip();
      var count = 0;
      this.pages.forEach(file => {
        Axios
          .get(file, {
            responseType: "blob"
          })
          .then(response => {
            zip.file(count+".jpg", response.data, {
              binary: true
            });

            ++count;

            if (count == this.pages.length) {
              zip
                .generateAsync({
                  type: "blob"
                })
                .then(function(content) {
                  saveAs(content, new Date() + ".zip");
                });
            }
          })
          .catch(error => {
            console.log(error);
          });
      });
    },
@iabdulazeem

This comment has been minimized.

Copy link

@iabdulazeem iabdulazeem commented Sep 13, 2019

Using Angular 2 :

1. I have installed the jzip-utils using the npm command
   npm install jszip-utils

2. When trying to include the reference in ***.ts file, i am getting a message  Cannot find module 'jszip-utils'

3. When observed the folder "node_modules", new folder 'jszip-utils' created with the required files

Any guidance will be great helpful.

Regards,
Srinivas

you have to import those npm libraries as following:
import { saveAs } from 'file-saver'
import * as JSZip from 'jszip'
import * as JSZipUtils from 'jszip-utils'

@Revthy

This comment has been minimized.

Copy link

@Revthy Revthy commented Nov 8, 2019

Using Angular 2 :

1. I have installed the jzip-utils using the npm command
   npm install jszip-utils

2. When trying to include the reference in ***.ts file, i am getting a message  Cannot find module 'jszip-utils'

3. When observed the folder "node_modules", new folder 'jszip-utils' created with the required files

Any guidance will be great helpful.
Regards,
Srinivas

you have to import those npm libraries as following:
import { saveAs } from 'file-saver'
import * as JSZip from 'jszip'
import * as JSZipUtils from 'jszip-utils'

You saved my time @azsidhu Thank You...

@varun952

This comment has been minimized.

Copy link

@varun952 varun952 commented Nov 10, 2019

But what about downloading files of size 5 GB , 10 GB etc. When I tried this examples, it actually reads all fiiles and writes to a zip. I am looking for a solution where a user should see a zip download happening immediately after download request

@Hussain-Safwan

This comment has been minimized.

Copy link

@Hussain-Safwan Hussain-Safwan commented Feb 18, 2020

I don't have actual files, but have text data (on database) and want to download the text data as files. Can I modify this method, somehow?

@modbender

This comment has been minimized.

Copy link

@modbender modbender commented Mar 3, 2020

How to solve CORS No 'Access-Control-Allow-Origin' for getBinaryContent? @noelvo

@soulinmaikadua

This comment has been minimized.

Copy link

@soulinmaikadua soulinmaikadua commented Mar 10, 2020

const Image = [
   "https://pngimage.net/wp-content/uploads/2018/06/react-icon-png-7.png",
   "https://cdn4.iconfinder.com/data/icons/logos-3/426/react_js-512.png",
   "https://cdn2.iconfinder.com/data/icons/designer-skills/128/react-512.png"
 ];

let count = 0;
    Image.forEach(function(url) {
      JSZipUtils.getBinaryContent(url, function(err, data) {
        if (err) {
          throw err;
        }
        zip.file(url, data, { binary: true });
        count++;
        if (count == Image.length) {
          zip.generateAsync({ type: "blob" }).then(function(content) {
            saveAs(content, "Image.zip");
          });
        }
      });

I try with this but it doesn't work

@tejojr

This comment has been minimized.

Copy link

@tejojr tejojr commented Jun 25, 2020

How to solve CORS No 'Access-Control-Allow-Origin' for getBinaryContent on nextjs?

@Arunwahatule85

This comment has been minimized.

Copy link

@Arunwahatule85 Arunwahatule85 commented Jun 27, 2020

Below is code in which i am creating data for csv file and downloading csv file in zip folder:

generateCSVfiles()
{

      this.service.getStudentDetails(studentid, student.name).subscribe
          (res => {
            var dataSet = (res);
            // start
            if (studentid == "Senior") {
             
              const header = ["studentId","StudentName"];
              const replacer = (key, values) => values === null ? '' : values // specify how you want to handle null values here
              this.seniordata = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
              this.seniordata.unshift(header.join(','));
              this.seniordata = this.seniordata.join('\r\n');
            }
            else if (studentid == "Junior") {
               const header = ["studentId","StudentName"];
              const replacer = (key, values) => values === null ? '' : values // specify how you want to handle null values here
              this.juniordata = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
              this.juniordata.unshift(header.join(','));
              this.juniordata = this.juniordata.join('\r\n');
               
            }
        this.downloadzip();
   }
}
   





public downloadzip()
{
	
	 let zip = new JSZip();
      // Fill CSV variable
      zip.file( 'Studentrecord'+'.csv', this.juniordata);
	  zip.file( 'Studentrecord'+'.csv', this.seniordata);
    
    zip.generateAsync({
      type: "base64"
    }).then(function (content) {
      window.location.href = "data:application/zip;base64," + content ;
    });

}

Above code working fine and able to download csv file inside zip folder when we got response data for one of junior or Senior student. but when we received both junior and senior data at time then it downloading different zip file or sometimes only one zip file getting generated. but i want both file in one zip folder. can someone guide me how to download different csv file in one zip folder.

@Kampadais

This comment has been minimized.

Copy link

@Kampadais Kampadais commented Jul 22, 2020

version 3
http://github.com/Stuk/jszip/zipball/master
https://stuk.github.io/jszip/
https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js

<script type="text/javascript" src="js/FileSaver.min.js"></script>
<script src="js/jszip.min.js" type="text/javascript">  </script>

var urls = [
                 "images/20170420_145140.jpg", 
                 "images/20170503_142841.jpg", 
                 "images/20170503_084035.jpg", 
                 "images/20170503_163354.jpg", 
                 "images/20170503_163334.jpg", 
                 "images/20170421_114806.jpg"];
var nombre = "Zip_img";
//The function is called
compressed_img(urls,nombre);

function compressed_img(urls,nombre) {
  var zip = new JSZip();
  var count = 0;
  var name = nombre+".zip";
  urls.forEach(function(url){
    JSZipUtils.getBinaryContent(url, function (err, data) {
      if(err) {
         throw err; 
      }
       zip.file(url, data,  {binary:true});
       count++;
       if (count == urls.length) {
         zip.generateAsync({type:'blob'}).then(function(content) {
            saveAs(content, name);
         });
       }
      });
  });
}

hello. I am using the version3 code to download a bunch of pdf from a database. I am using some big paths and those paths are creating the whole folder heirarchy on the zip. Is there a way to just put them on the top of the zip and not creating useless folders?

@swethakrgs

This comment has been minimized.

Copy link

@swethakrgs swethakrgs commented Sep 2, 2020

Hey Thank you all below code is working fine for me
var urls = [
"images/20170420_145140.jpg",
"images/20170503_142841.jpg",
"images/20170503_084035.jpg"];
download() {

        urls.forEach(function (url) {
            JSZipUtils.getBinaryContent(url, function (err, data) {
                if (err) {
                    throw err; // or handle the error
                }
                try {
                    zip.file(count + ".jpg", data, { binary: true });
                    count++;
                    if (count == urls.length) {
                        zip.generateAsync({ type: "blob" }).then(function (content) {
                            FileSaver.saveAs(content, zipFilename);
                        });
                    }
                } catch (e) {
                    console.log("errorrr...k", e)
                }
            });
        });
    }

The mistake I did is zip.file("image", data, { binary: true });
I am passing three URLs but adding name static so it is downloading one file. after changing the name dynamically it is working.

@AnjushaJoshi

This comment has been minimized.

@Ishaan28malik

This comment has been minimized.

Copy link

@Ishaan28malik Ishaan28malik commented Feb 27, 2021

I just created a new App using the multiple-file-downloader

Here

https://github.com/Ishaan28malik/react-zip-download

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment