在下载 javascript 之前,多个下载链接指向一个 zip 文件 [英] Multiple download links to one zip file before download javascript

查看:32
本文介绍了在下载 javascript 之前,多个下载链接指向一个 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 javascript 中,是否可以将多个下载 url 发送到一个 zip 文件中,并且可以下载该 zip 文件.几乎,在我的网页上,有一个按钮,点击后会下载一个 zip 文件,其中包含来自下载 url 的所有文件压缩成 zip 文件?

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?

我相信我需要使用 jszip 或类似的工具.这完全可能吗?有什么关于从哪里开始的建议吗?

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?

推荐答案

你可以使用 JSZip.js, XMLHttpRequest(), Array.prototype.map() , Promise.all() 在所有文件请求完成后创建 .zip 文件;使用 元素,将 download 属性设置为 .zip 文件的 objectURL JSZip .generateAsync() 函数,点击 a 元素应显示 Save File 对话框,其中包含创建的 .zip作为可下载的文件.

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

这篇关于在下载 javascript 之前,多个下载链接指向一个 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆