res.download()在我的情况下不工作
我正在使用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.
如何将文件保存在本地磁盘中? / p>
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 )
编辑:,因为您要求 / download
通过AJAX调用,您必须更改设置,因为大多数(所有?)浏览器在这种情况下不会显示下载对话框。
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');