Express render view and download file at the same time

て烟熏妆下的殇ゞ 提交于 2021-01-29 09:39:38

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/52112919/express-render-view-and-download-file-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!