问题描述
我正在使用 nodejs 和 expressjs 框架从服务器下载文件jsonFile.json".
I am using nodejs and expressjs framework to download a file 'jsonFile.json' from server.
我正在使用以下代码
res.get('/download', function(req, res) {
res.setHeader('Content-disposition', 'attachment; filename=jsonFile.json');
res.setHeader('Content-Type', 'text/json');
res.download(__dirname + 'jsonFile.json');
}
});
但这会导致响应文件的全部内容.
But this results into a response with whole content of file.
我期待浏览器要求我将文件保存在本地磁盘中.
i was expecting browser to ask me to save the file in local disk.
如何将文件保存在本地磁盘中????
How do i save the file in local disk.???
推荐答案
让 Express 设置正确的标题,然后这样做:
Let Express set the correct headers and just do this:
res.get('/download', function(req, res) {
res.download(__dirname + 'jsonFile.json', 'jsonFile.json');
});
(doc)
由于您通过 AJAX 调用请求 /download
,您必须更改设置,因为大多数(所有?)浏览器不会显示下载对话框在那种情况下.
since you're requesting /download
through an AJAX call, you have to change your setup because most (all?) browsers will not show a download dialog in that case.
相反,您可以从前端代码创建一个新窗口来触发对话框:
Instead, you can create a new window from your front end code to trigger the dialog:
window.open('/download?foo=bar&xxx=yyy');
这篇关于res.download() 在我的情况下不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!