How to download multiple audio filles in JsZip

Tags:



I want to download all audio files from folder but this code only download last file in folder.

var element = document.getElementById("songs");

      var audionum = element.getElementsByTagName('audio').length;

      var zipcounter = 0;

      var zip = new JSZip();

      var zipName = 'Test.zip';

      for(var i = 0; i < audionum; i++){
        var audiosrc  = document.getElementsByTagName('source')[i].getAttribute("src");
        var audiosrcsplit = audiosrc.split('/')[1];        
        // loading a file and add it in a zip file
        JSZipUtils.getBinaryContent(audiosrc, function (err, data) {
           if(err) {
              throw err; // or handle the error
           }
           zip.file(audiosrcsplit, data, {binary:true});
           zipcounter++;
           if (zipcounter == audionum) {
             zip.generateAsync({type:'blob'}).then(function(content) {
                saveAs(content, zipName);
           });
          }
        });
      }

Answer

For ES6 , you can try replacing var with let (block scope).

If you are making use of ES5 then, try something like below.

var element = document.getElementById("songs");
var audionum = element.getElementsByTagName('audio').length;
var zipcounter = 0;
var zip = new JSZip();
var zipName = 'Test.zip';
function addToZip(audiosrc, audiosrcsplit) {
    JSZipUtils.getBinaryContent(audiosrc, function (err, data) {
        if (err) {
            throw err; // or handle the error
        }
        zip.file(audiosrcsplit, data, {
            binary: true
        });
        zipcounter++;
        if (zipcounter == audionum) {
            zip.generateAsync({
                type: 'blob'
            }).then(function (content) {
                saveAs(content, zipName);
            });
        }
    });
}
for (var i = 0; i < audionum; i++) {
    var audiosrc = document.getElementsByTagName('source')[i].getAttribute("src");
    var audiosrcsplit = audiosrc.split('/')[1]; // loading a file and add it in a zip file
    addToZip(audiosrc, audiosrcsplit);
}



Source: stackoverflow