Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you serve a file without leaving the page?

Aims

I'm trying to let users download a file (myfile.zip in this case) by clicking a button on the page, without them leaving the page - ie the browser must stay on the current page, and leave them in a position where they can continue to use the page, including clicking the button again (should they wish to get a new copy of the file).

I need this to work across all browsers (IE6-8, Firefox, Chrome, Opera, Safari).

Background

Packaged inside the zip is a selection of stuff based on their other interactions (some of which may be partially complete) from the same page (this is all done via ajax) and I don't want them to leave the page as they would lose any unsaved changes.

like image 832
PeterJCLaw Avatar asked Mar 03 '09 01:03

PeterJCLaw


2 Answers

Add the following header when the download file is served:

Content-disposition: attachment; filename=filename.zip

Most browsers will wait to see what type of thing they are loading before they clear the current page, and if it something that should be downloaded as a file they won't navigate away from the current page (they'll show a Save As dialog in front of the page, which can be dismissed to return to the page).

If however you find that a certain browser does navigate away from the current page, you may try having the link to the download contained in a small iframe, so only that frame changes.

I think it's a better solution to opening the link in a new window, because some browsers will leave the new window up even once it's determined that it is a file that should be downloaded, so you end up with a blank window.

like image 99
thomasrutter Avatar answered Oct 11 '22 16:10

thomasrutter


If you make the link open in a new window/tab (e.g. via the <a> tag's target="_blank" attribute), it won't disturb the contents of the current window.

The target attribute is deprecated, but widely supported. Depending on the browser, you may also be able to use the CSS3 target-name property.

If your goal is to absolutely guarantee that the main window is undisturbed, this is likely the safest method, as it's resilient against download errors.

like image 3
Anirvan Avatar answered Oct 11 '22 16:10

Anirvan