1

I have a download button in HTML that when is clicked a POST request is made via ajax sending the filename of the file that must be downloaded.

On the server side I do something like this:

function download (req, res) {

    ...
    // path is an absolute path to a file that is not in the public
    // directory. I want to download that file
    res.writeHead(200, {
        "Content-disposition": "attachment;filename=\"" + path + "\"",
        "Content-Type": "text/csv"
    });

    var filestream = fs.createReadStream(path);
    filestream.pipe(res);
};

I can see the file content in the response but the save file dialog doesn't appear.

Which is the issue? How can I fix this?

I use only built-in node modules, so I don't use express.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

1

You can't force a browser to show a Save File dialog.

With your example, on my Mac both Chrome and Safari download the file automatically (in Chrome it's a setting whether or not to show a dialog which – I think – is turned off by default; I don't know if Safari has a similar setting), whereas FireFox does give me a dialog.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • I used this code to test: [gist](https://gist.github.com/robertklep/9c0fbead7afabd792978) – robertklep Oct 16 '13 at 13:36
  • @Johnツ sounds like there's another issue somewhere else in your code – robertklep Oct 16 '13 at 13:42
  • @Johnツ oh right I completed missed that. In that case, it's going to be even more difficult because AJAX requests cannot trigger a download AFAIK (see [this question and answers](http://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post) for some tips, though) – robertklep Oct 16 '13 at 13:50
  • Works good using the form method: `$("
    ")...`, append inputs, and submit it. Please add this content to your answer to vote it and mark it! :-) Thanks!
    – Ionică Bizău Oct 16 '13 at 14:07
  • @Johnツ I wouldn't want to take credit for other peoples solutions :) – robertklep Oct 16 '13 at 14:09