res.download()在我的情况下不工作 [英] res.download() not working in my case

查看:206
本文介绍了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');

这篇关于res.download()在我的情况下不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆