Skip to content

Instantly share code, notes, and snippets.

@noelvo
Created December 6, 2015 23:22
Show Gist options
  • Star 53 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save noelvo/4502eea719f83270c8e9 to your computer and use it in GitHub Desktop.
Save noelvo/4502eea719f83270c8e9 to your computer and use it in GitHub Desktop.
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);
}
});
});
@Hussain-Safwan
Copy link

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
Copy link

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

@soulinmaikadua
Copy link

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

@zeroonedev01
Copy link

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

@Arunwahatule85
Copy link

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
Copy link

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
Copy link

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
Copy link

@Ishaan28malik
Copy link

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