1

I'm not able to return a file, when submitting a HTTP post

I know that all of my code is functioning, up until the download / sendfile part.

var postData = req.body;
var outputString = "";

mkdirp('./server/tmp');

_.each(postData, function (each) {
    outputString += each.variable + ":  " + each.value + " !default;\n";
});

fs.writeFile(path.resolve("./server/tmp/ionic.app.scss"), outputString);

res.attachment(path.resolve("./server/tmp/ionic.app.scss"));
res.end('hello,world\nkeesun,hi', 'UTF-8');

How can I make it so that, when the user clicks a button, it sends a POST request, which in turn downloads a file that is created on the fly by the node server?

Paolo Bernasconi
  • 2,010
  • 11
  • 35
  • 54

1 Answers1

1

res.attachment() only sets the content disposition header. Use res.download() instead.

res.download(path.resolve("./server/tmp/ionic.app.scss"));

res.download() both sets the content disposition header and sends the file.

-- EDIT --

Like I mentioned in my last comment, I failed to mentioned that you should remove the final res.end() in your code.

I'm wondering, though, why you're saving the generated text to a file just to send it. A simplified way of doing it would be as follows:

var postData = req.body;
var outputString = "";

mkdirp('./server/tmp');

_.each(postData, function (each) {
    outputString += each.variable + ":  " + each.value + " !default;\n";
});


res.attachment("ionic.app.scss");
res.send(outputString);
res.end();

This will accomplish the same goal, without having to save the outputString to a file first.

JME
  • 3,592
  • 17
  • 24
  • hmm, I've done that now, and I see `Content-Disposition:attachment; filename="ionic.scss"` in my response header, but still no file is being downloaded (no initiation). Any idea why? – Paolo Bernasconi Sep 14 '14 at 19:58
  • Paolo, I just did a test and it worked for me. The only difference in my code is that I don't have the `res.end()` that you have at the end of your code. I suggest you remove it. – JME Sep 15 '14 at 22:41
  • I've added a working example at [Runnable](http://runnable.com/VBeBCkl1te08g8uN/express-http-post-download-example-for-node-js-and-express-js) for you to checkout. – JME Sep 16 '14 at 00:18
  • Thanks for the example! I realized that I was having an issue with using a HTTP GET + javascript, which is similar to: http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – Paolo Bernasconi Sep 16 '14 at 03:31