Multiple download links to one zip file before download javascript

You can use JSZip.js, XMLHttpRequest(), Array.prototype.map() , Promise.all() to create .zip file when all requests for files have completed; use <a> element with download attribute set to objectURL of .zip file at JSZip .generateAsync() function, click on a element should display Save File dialog with created .zip as downloadable file.

<head>
  <script src="https://stackoverflow.com/questions/37176397/jszip.js"></script>
  <script>
    window.onload = function() {
      var zip = new JSZip();
      var a = document.querySelector("a");
      var urls = ["a.html", "b.html"];

      function request(url) {
        return new Promise(function(resolve) {
          var httpRequest = new XMLHttpRequest();
          httpRequest.open("GET", url);
          httpRequest.onload = function() {
            zip.file(url, this.responseText);
            resolve()
          }
          httpRequest.send()
        })
      }

      Promise.all(urls.map(function(url) {
          return request(url)
        }))
        .then(function() {
          console.log(zip);
          zip.generateAsync({
              type: "blob"
          })
          .then(function(content) {
            a.download = "folder" + new Date().getTime();
            a.href = URL.createObjectURL(content);
            a.innerHTML = "download " + a.download;
          });
        })
    }
  </script>
</head>

<body>
  <a href="" download>download</a>
</body>

plnkr http://plnkr.co/edit/baPtkILg927DtJfh4b5Y?p=preview

Leave a Comment