How do you serve a file without leaving the page? How do you serve a file without leaving the page? ajax ajax

How do you serve a file without leaving the page?


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.


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.


To avoid leaving the page (if you do this the page tries to close itself first, so that it's sure that you've saved everything, and you get warning messages if you haven't) or leaving blank tabs (which I don't like, nor the use of the depreciated target attribute) I've used an iframe, whose src attribute is changed in javascript.

This works everywhere except some versions of Opera, which I have considered an acceptable loss (I might fix that via the use of one of the other solutions plus browser detection later).