Carol Skelly
Carol Skelly

Reputation: 362360

NodeJS, Express - Render EJS view to a download file

I have a NodeJS, Express 3 app that uses EJS templating. I have a route that enables 'preview' of some form fields containing HTML and CSS that are posted. It simply plugs them in and renders my preview.ejs template like this..

app.post('/preview', function(req, res){

    var htm = req.body.htm;
    var css = req.body.css;

    res.render('preview',{_layoutFile:'', htm:htm, css:css});
});

What I'd like to do now is a similar route that forces download of the file instead..

app.post('/download', function(req, res){

    var htm = req.body.htm;
    var css = req.body.css;

    // res.download or res.sendfile here ??
});

I see that there is a res.sendfile() and res.download(), but how can I use these with my EJS 'preview' view template?

P.S. - I'm also using Mikeal's request is this same app. I wonder if there is a way I could use pipe to fs (filesystem) and then force download of the saved file?

Upvotes: 1

Views: 3063

Answers (1)

Plato
Plato

Reputation: 11052

See: http://expressjs.com/api.html#res.attachment

res.attachment() sets Content-Disposition: attachment header which tells the browser to treat the response as a download.

app.post('/download', function(req, res){

    var htm = req.body.htm;
    var css = req.body.css;

    res.attachment();
    res.render('preview',{_layoutFile:'', htm:htm, css:css});
});

Upvotes: 2

Related Questions