Paolo Bernasconi
Paolo Bernasconi

Reputation: 2030

Node Express - Http post to return a file

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?

Upvotes: 1

Views: 4980

Answers (1)

JME
JME

Reputation: 3632

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.

Upvotes: 1

Related Questions