【问题标题】:Unable to send file with PDF( *.pdf) extension无法发送带有 PDF(*.pdf) 扩展名的文件
【发布时间】:2020-01-24 06:53:45
【问题描述】:

我正在尝试使用节点的 readFile 方法读取文件,然后将其作为响应发送,以便用户可以下载它。

这是我的代码:

async function(req, res, next) {
const query = { id: req.params.id };
// @ts-ignore
const fileURL = await Patient.findOne(query).select('retinaReportURL -_id');

// @ts-ignore
const splittedPath = fileURL.retinaReportURL.split('\\');
const fileName = splittedPath[splittedPath.length-1].split('.')[0] + '.pdf';

const filePath = path.join(__dirname, '..', '..', 'Invoices', fileName);

fs.readFile(filePath, (err, _data) => {
  if (err) {
    return next(new APIError('Unable to fetch file at the moment please try again later', 500))
  }
  res.send(data);
});

}

现在我的文件路径是正确的,并且 Invoices 文件夹中有一个有效的 PDF。

但是,当文件被下载时,我面临两个问题:

  1. .pdf 扩展名不存在。
  2. 下载它的文件名是我作为请求参数传递的id

我尝试将响应标头设置为text/pdf,但没有成功。

我在这里做错了什么??

【问题讨论】:

  • 更改 res.send(data);到 res.send(_data); _data 你使用的权利
  • id 有什么问题?
  • @PrakashKarena 对不起,我写错了_data,它实际上是我代码中的数据。
  • @Sohan id 本身没有问题,只是下载的没有扩展名的文件的名称等于 id 和该文件夹中的实际文件名

标签: javascript node.js typescript express


【解决方案1】:

Express 有一个helper ,方便您使用,

我假设你有以下路径,

     const fileName = splittedPath[splittedPath.length-1].split('.')[0] + '.pdf';   
     const filePath = path.join(__dirname, '..', '..', 'Invoices', fileName);
     app.get('/download', function(req, res)
     {          
      res.download(filePath); // Set file name with its path
     });

【讨论】:

  • 嘿,谢谢@Sohan,你的回答帮助了我,我现在可以下载文件了 :) :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 2021-08-25
  • 2014-05-23
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 2014-10-19
相关资源
最近更新 更多