Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

javascript - res.download() not working in my case

I am using nodejs and expressjs framework to download a file 'jsonFile.json' from server.

i am using the following code

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.???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let Express set the correct headers and just do this:

res.get('/download', function(req, res) {
  res.download(__dirname + 'jsonFile.json', 'jsonFile.json');
});

(doc)

EDIT: 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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...