首页 > 解决方案 > 使用 node js 下载文件

问题描述

我正在使用带有节点 js 的打字稿并尝试将下载添加到服务器。我已将上传的文件保存在 public/data/uploads 文件夹中。

export const downloadFile: RequestController = (req, res) => {
  try {
    const fileName = req.params.name;
    console.log(path.join(__dirname));

    const directoryPath = "../../public/data/uploads";

    return res.download(directoryPath + fileName, fileName, (err) => {
      if (err) {
        res.status(500).send({
          message: "Could not download the file. " + err,
        });
      }
    });
  } catch (error) {
    console.log(error);
    return res.status(500).json("Internal server error");
  }
};

每当我尝试运行这个控制器时,它都会抛出一个错误说 "message": "Could not download the file. Error: ENOENT: no such file or directory, stat '/home/bishal/Projects/Ticketing System/backend/build/controllers/public/data/uploads2006222-A-A-Milne-Quote-Promise-me-you-ll-always-remember-You-re-braver.jpg'"

那么如何在这里正确地给出文件夹方向。我的公用文件夹在构建文件夹之外

我怎样才能到达

标签: typescriptfiledownload

解决方案


推荐阅读