Javascript 无法发送扩展名为PDF(*.PDF)的文件

Javascript 无法发送扩展名为PDF(*.PDF)的文件,javascript,node.js,typescript,express,Javascript,Node.js,Typescript,Express,我正在尝试使用node的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 splittedPa

我正在尝试使用node的
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

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

  • .pdf扩展名不存在
  • 下载文件的文件名是作为请求参数传递的id
  • 我尝试将响应标题设置为
    text/pdf
    ,但没有成功

    我在这里做错了什么???

    Express有一个解决方案,可以让您更轻松

    我想你有一条路要走

         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
         });
    

    更改res.send(数据);重新发送(_数据)_您使用的数据是否正确
    id
    有什么问题?@PrakashKarena抱歉,我错写了_data,它实际上是我代码中的数据。@Sohan id本身没有问题,只是下载的文件没有扩展名,其名称与id和实际文件名相同。谢谢@Sohan,你的回答帮助了我,我现在可以下载文件了:):)