Download multi images in zip file via url list

Say You have a table contains many picture link, you can create a query and download them in one zip files. Here is a code snippet

function urlToPromise(url) {
  return new Promise(function(resolve) {
    JSZipUtils.getBinaryContent(url, function (err, data) {
      if(err) {
        console.error(`Error fetching ${url}:`, err);
        resolve(null); // Resolve with null in case of error
      } else {
        resolve(data);
      }
    });
  });
}

var zip = new JSZip();
zip.file("ReadMe.txt", "Hello World\n");
var outputFiles = zip.folder("files");
var promises = [];

for(var i = table1.selectedDataIndex; i < table1.selectedDataIndex + 100; i++){
  (function(index) {
    promises.push(urlToPromise(table1.data[index].imageLink)
      .then(function(data) {
        if(data) { // filter the null file
          outputFiles.file(table1.data[index].productId  + ".jpg", data, {binary:true});
        }
      }));
  })(i);
}

Promise.all(promises).then(function() {
  zip.generateAsync({type:"blob"})
  .then(function callback(blob) {
    // see FileSaver.js
    saveAs(blob, "example" + Math.random() + ".zip");
  });
});

Here is referrence js library
https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js
https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js
https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.1.0/jszip-utils.min.js

And here is download file should be like.

1 Like

This is great! Thanks for sharing, @AnsonHwang!