jszip 仅从 url 压缩两个文件之一

Nic*_*ver 4 javascript jszip

我正在尝试使用 jszip 插件从 URL 压缩两个文件,但遇到了一些问题。我正在尝试从一个 url 压缩两个文件(当前使用 imgur 链接进行测试),但是只有一个文件被压缩。我不确定我的 foreach 函数是否做错了什么?

任何建议都会很棒谢谢。

function urlToPromise(url) 
{
    return new Promise(function(resolve, reject) 
    {
        JSZipUtils.getBinaryContent(url, function (err, data) 
        {
            if(err) 
            {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

(function () 
{
  var zip = new JSZip();
  var count = 0;
  var zipFilename = "instasamplePack.zip";
  var urls = [
    'https://i.imgur.com/blmxryl.png',
    'https://i.imgur.com/Ww8tzqd.png'
  ];

  function bindEvent(el, eventName, eventHandler) {
    if (el.addEventListener){
      // standard way
      el.addEventListener(eventName, eventHandler, false);
    } else if (el.attachEvent){
      // old IE
      el.attachEvent('on'+eventName, eventHandler);
    }
  }

  // Blob
  var blobLink = document.getElementById('kick');
  if (JSZip.support.blob) {
    function downloadWithBlob() {

      urls.forEach(function(url){
        var filename = "element" + count + ".png";
        // loading a file and add it in a zip file
        JSZipUtils.getBinaryContent(url, function (err, data) {
          if(err) {
            throw err; // or handle the error
          }
          zip.file(filename, urlToPromise(urls[count]), {binary:true});
          count++;
          if (count == urls.length) {
            zip.generateAsync({type:'blob'}).then(function(content) {
              saveAs(content, zipFilename);
            });
          }
        });
      });
    }
    bindEvent(blobLink, 'click', downloadWithBlob);
  } else {
    blobLink.innerHTML += " (not supported on this browser)";
  }

})();
Run Code Online (Sandbox Code Playgroud)

Dav*_*hel 5

当你这样做时

urls.forEach(function(url){
  var filename = "element" + count + ".png";               // 1
  JSZipUtils.getBinaryContent(url, function (err, data) {
    count++;                                               // 2
  });
});
Run Code Online (Sandbox Code Playgroud)

您执行1两次,下载完成后调用2. count在这两种情况下(在 )仍然为零1,您可以用另一个图像(相同名称)覆盖一个图像。

您还可以将每个图像下载两次:urlToPromise已经调用JSZipUtils.getBinaryContent.

要解决这个问题:

  • 使用forEach 回调的索引参数而不是count
  • JSZip 接受承诺(并在内部等待它们),urlToPromise已经转换所有内容:使用它
  • 不要试图等待承诺,JSZip 已经做到了

这给出了一个新downloadWithBlob函数:

function downloadWithBlob() {
  urls.forEach(function(url, index){
    var filename = "element" + index + ".png";
    zip.file(filename, urlToPromise(url), {binary:true});
  });
  zip.generateAsync({type:'blob'}).then(function(content) {
    saveAs(content, zipFilename);
  });
}
Run Code Online (Sandbox Code Playgroud)