Document generation, force download, and refresh page

248 Views Asked by At

I'm not sure how to do it all the best way (just PHP, PHP + javascript...):

I must allow the user to send some form data which generates a report file that becomes listed together with others previously generated, each one with a link to download it. I'd like to allow the user the choice to save it just after generation (content-disposition header). In case they don't want, the link will still be available in the list.

So, I tried doing it by sending a "Content-Disposition: attachment" header. Everything works great (file stored in server for further availability from the mentioned links, and it is also sent to the user so that they can store it in their system at once). The problem is that the reports list won't be updated with the new report because I can't get the refreshed HTML in the response at the same time (could I?).

I've tried sending a Location header also, but this seems to break the previous funcionality.

You may think I'm an idiot, but in my effort to display the newly created file in the list after sending the form, I've also tried using javascript instead of the Content-Disposition header, so that once the file is created, a script calls window.open(), but this caused to open the file (a CSV file) in the browser as it is: pure plain text. My other alternative in mind is to serve the HTML with the newly created report firstly, plus a script which makes a second call through ajax to the server, then PHP sends back the Content-Disposition header with the file content this time. But this seems too much twisted to me. Or is it the best and most common way to do this in a sole user interaction?

What do you think?

1

There are 1 best solutions below

1
On

I would use your method where you return the file name via AJAX and then use the window.open() but with this create a .htaccess file where you are storing your .csv files and add AddType application/octet-stream .csv which should force a download.