0

I would like to use express to render a file AND download a file at the same time

My current code is as follows:

res.attachment('filename.csv');
res.render('pages/result', { data });

However, if I do this, it only downloads the data and does not render the view

What I want is to render a success page, and then send the file so that it downloads

I need this to be done with 1 endpoint, because, I need to generate the file and only if it is successful, I would render the success page

Am I able to do this with 1 endpoint?

Thank you

user123
  • 99
  • 1
  • 11

2 Answers2

0

Don't think doing both is possible in 1 endpoint. What you can do is that, whenever you want to download the file place a js code to download the file inside the ejs template in a condition so that it is only downloaded whenever you want.

deepak thomas
  • 1,118
  • 9
  • 23
  • The issue I have with this, is that, I need to generate the file and make an api call, and only if it is successful, I would render the success page – user123 Aug 31 '18 at 10:14
  • the rendered page is in your control right, you can declare a js variable (using ejs templating) with path in script tag which you have wrapped inside condition of ejs – deepak thomas Aug 31 '18 at 12:11
0

send the path of the file to the render page as variable and write a function in javascript to download the file automatically.

res.render('pages/result', { path: '../folder/filename.csv'});

on render page

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
    document.getElementById('my_iframe').src = #{path};
};
</script>

Download File Using Javascript/jQuery

Pavan Nath
  • 1,494
  • 1
  • 14
  • 23