【问题标题】:How to add files using JSZip from remote URL in ReactJS?如何使用 JSZip 从 ReactJS 中的远程 URL 添加文件?
【发布时间】:2020-04-19 08:48:10
【问题描述】:

我正在使用 map 函数在我的 zip 文件的文件夹中循环文件,但该文件夹始终为空。主文件的获取虽然有效。

这是我的代码:

getZip = async () => {
  const zip = new JSZip();

  const url = await svc.getMainFileURL();  // will return a downloadable url from s3
  let response = await fetch(mcsURL);      // will fetch the data from s3 blob
  let data = await response.blob();        // and convert it into blob

  zip.file(`MainFile.xlsx`, data);         // add into the zip file

  const otherFiles = zip.folder("files");  // create another folder inside the zip file

  // Loop files from source data then insert it in the folder
  const list = sourceData.map(async (item,index) => {
    const fileUrl = await svc.getOtherFileUrl();

    const response = await fetch(fileUrl);
    const data = await response.blob();
    console.log(data);
    otherFiles.file(`${index}.xlsx`, data);
  })

  zip.generateAsync({type:"blob"})
  .then(function(content) {
      FileSaver.saveAs(content, `Zip File Name`);
  });
}

数据记录返回正常,但是当我下载 zip 文件时,它只有主文件的数据和文件夹文件。截图如下:

我使用 async/await 可能有问题,但我无法弄清楚。谁能帮我?提前致谢。

【问题讨论】:

    标签: reactjs jszip


    【解决方案1】:

    没关系,我已经使用Promise.all() 解决了它。 zip.generateAsync 函数会返回 zip 文件,即使 map 函数中的 promise 没有被解析。这就是为什么文件夹总是空的。这是我修改后的代码:

    getZip = async () => {
      const zip = new JSZip();
    
      const url = await svc.getMainFileURL();  // will return a downloadable url from s3
      let response = await fetch(mcsURL);      // will fetch the data from s3 blob
      let data = await response.blob();        // and convert it into blob
    
      zip.file(`MainFile.xlsx`, data);         // add into the zip file
    
      const otherFiles = zip.folder("files");  // create another folder inside the zip file
    
      // Loop files from source data then insert it in the folder
      const list = sourceData.map(async (item,index) => {
        const fileUrl = await svc.getOtherFileUrl();
    
        const response = await fetch(fileUrl);
        const data = await response.blob();
        console.log(data);
        otherFiles.file(`${index}.xlsx`, data);
        return data;
      })
    
      // If all prmises are fullfilled it will call the zip 
      // function and download it using the FileSaver library
      Promise.all(list).then(function() {
        zip.generateAsync({type:"blob"})
        .then(function(content) {
          FileSaver.saveAs(content, `Zip File Name`);
        });
      }); 
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多