jszip 仅压缩 url 中的两个文件之一

jszip only zipping one of the two files from url

我正在尝试使用 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)";
  }

})();

当你做的时候

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

你执行 1 两次,当下载完成时你调用 2。在这两种情况下 count 仍然为零(在 1),您用另一张图像覆盖另一张图像(同名)。

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

解决这个问题:

  • 使用 index parameter of the forEach callback 代替 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);
  });
}