Multiple download links to one zip file before download javascript

Dude1310 picture Dude1310 · May 12, 2016 · Viewed 18.3k times · Source

Is it possible, in javascript, to have multiple download urls sent into one zip file and that zip file can be downloaded. So pretty much, on my web page, there is one button, that when clicked downloads a zip file of all the files from the download urls compressed into the zip?

I believe I'd need to use jszip or some tool like that. Is this at all possible and is there any advice on where to start?

Answer

guest271314 picture guest271314 · May 12, 2016

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="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