gpt4 book ai didi

node.js - Express.js 中的 res.download 文件发生了什么?

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:01 24 4
gpt4 key购买 nike

我正在开发一个应用程序,该应用程序在服务器上创建 PDF 文档,然后显示在此处下载按钮。当我单击该按钮时,该过程似乎有效。当我检查 Chrome 控制台中的“网络”>“预览”和“网络”>“ header ”选项卡时,我可以看到该文件肯定已返回。

问题是,它不显示,也不提供保存选项。我在这里错过了客户端步骤吗?我首选的结果是让用户选择保存文件或自动开始下载到默认路径。

这是相关的服务器代码:

exports.show = function(req, res) {
var file = req.params.id;
var filePath = __dirname + '../../../lib/completedforms/';
var thisPath = path.resolve(filePath + file);
res.attachment(thisPath);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader("Content-Disposition", "attachment");
res.download(thisPath);
};

预先感谢您在此提供的任何指导。

最佳答案

不需要同时使用res.attachment()res.download()。只需使用后者即可。

此外,res.download() 已经设置了 Content-Disposition header ,因此您也可以将其删除。

您还可以简化路径生成:

var thisPath = path.resolve(__dirname, '../../../lib/completedforms/', file);

尽管您可能应该清理file 和/或检查thisPath 是否不在不应该出现的位置。这将防止有人提供潜在的恶意 req.params.id 值,例如 ../../../../../../../etc/passwd .

关于node.js - Express.js 中的 res.download 文件发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com