jszip仅从url压缩其中一个文件

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

})();
1个回答

5

当你执行时

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

你执行1两次,当下载完成时调用2。在这两种情况下(在1处),count仍为零。你用一个图片覆盖了另一个(同名)。
你还下载了每个图像两次:urlToPromise已经调用了JSZipUtils.getBinaryContent
要解决这个问题:
  • 使用forEach回调的{{link1:索引参数}}代替count
  • JSZip接受promise(并在内部等待它们),urlToPromise已经将所有内容转换:使用它
  • 不要尝试等待promise,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);
  });
}

谢谢,你重写的downloadWithBlob正是我所需要的。 - Ralph Dell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接