【问题标题】:Archive multiple files with Node and download it immediately使用 Node 归档多个文件并立即下载
【发布时间】:2019-10-15 12:48:23
【问题描述】:

我正在尝试在服务器上压缩多个文件并在用户请求时下载它。我正在使用 adm-zip 压缩文件。

文件添加得非常好并且被压缩。 zip.writeZip('') 完美压缩文件并将它们保存到本地服务器。我只是无法下载它们。无论哪种方式,我认为如果我可以直接通过缓冲区发送 zip 会更好。

router.get(
  "/download-zip/:season_id/:club_id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    FileSubmission.find({
      season: req.params.season_id,
      club: req.params.club_id
    }).then(files => {

      const zip = new AdmZip();

      files.forEach(file => {
        // add local file
        zip.addLocalFile(`uploads/club-uploads/${file.club}/${file.name}`);
      });

      res.download(zip.toBuffer(), "asd.zip");
    });
  }
);

在前面我使用的是 react with actions 和 js-file-download 库


// Download ALL FILES by season ID and club ID
import fileDownload from "js-file-download";

export const downloadAllFiles = (season_id, club_id) => dispatch => {
  axios
    .get(`/api/files/download-zip/${season_id}/${club_id}`)
    .then(response => {
      fileDownload(response.data, `All Files- ${club_id}.zip`);
    })
    .catch(err => {
      console.log(err);
      dispatch({ type: GET_ERRORS, payload: err.response.data });
    });
};

【问题讨论】:

  • 查看您的代码,它似乎不是 async.. 这里只是一个大警告,如果使用 express 并且压缩的内容很大,那么您的 Web 应用程序的所有用户都会受到影响。也许考虑将其中的一些转移到某种集群或服务器工作者中。 Ps,将您的网络服务器也使用集群只会意味着它将问题转移到连接到特定集群的所有用户。

标签: javascript node.js express download adm-zip


【解决方案1】:

这是我设法创建临时存档、下载并删除它的方法。

这里是后端

// Create a ZIP of files uploaded by a club
router.get(
  "/download-zip/",
  (req, res) => {
      zip.addLocalFile(/*ADD THE FILES TO ZIP*/);

      zip.writeZip(
        `temp/zips/temp-file.zip`,
        err => {
          if (err) {
            console.log(err);
          }

          res.download(
            `uploads/club-zips/test-file.zip`,
            function(err) {
              if (!err) {
                //delete file after it's been downloaded
                fs.unlinkSync(
                  `uploads/club-zips/test-file-${req.params.club_id}.zip`
                );
              }
            }
          );
        }
      );
    });
  }
);

这是我在前面使用的。正如我所说,我使用名为 js-file-download 的包来下载 blob

export const downloadAllFiles = () => dispatch => {
  axios
    .get(`/api/files/download-zip/`, {
      responseType: "arraybuffer"
    })
    .then(response => {
      fileDownload(response.data, `all-files.zip`);
    })
    .catch(err => {
      console.log(err);
    });
};

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多