带有http路径的jszip下载文件

时间:2018-09-11 13:15:17

标签: javascript jquery html5 jszip

我尝试用images的本地主机下载url

我的代码在这里

<head>
  <script src="Stuk-jszip-9fb481a/dist/jszip.js"></script>
  <script>
    window.onload = function() {
      var zip = new JSZip();
      var a = document.querySelector("a");
      var urls = ["http://localhost/cce/assests/images//save_img.png"];

      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>

,但使用其创建文件夹http来存储图像

在控制台中显示,例如

http:/
:
ZipObject {name: "http:/", dir: true, date: Tue Sep 11 2018 18:39:38 GMT+0530 (India Standard Time), comment: null, unixPermissions: null, …}
http://localhost/
:
ZipObject {name: "http://localhost/", dir: true, date: Tue Sep 11 2018 18:39:38 GMT+0530 (India Standard Time), comment: null, unixPermissions: null, …}

1 个答案:

答案 0 :(得分:0)

尝试此代码

<head>
  <script src="Stuk-jszip-9fb481a/dist/jszip.js"></script>
  <script>
    window.onload = function() {
      var zip = new JSZip();
      var a = document.querySelector("a");
      var urls = ["http://localhost/cce/assests/images//save_img.png"];

    const toDataURL = url => fetch(url)
      .then(response => response.blob())
      .then(blob => new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onloadend = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsDataURL(blob)
      }));


      function request(url) {
        return new Promise(function(resolve) {
          toDataURL(url)
              .then(dataUrl => {
                zip.file("image.png", dataUrl.substr(dataUrl.indexOf(',')+1), {base64: true});
                resolve()
              });
              })
      }

      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>