After a week, I now have a better understanding that is going on, and I want to share it with people who need.
Actually, it depends both on the server side for response and how the browsers will handle that response.
For example,
form
, using target
attribute which the default is _self
to redirect user from link to link, and client side will implement how to handle response return from server.
iframe
, similarly server will return a response and client side must know how to handle that response, it could redirect the user to another page by automatically refresh its iframe, or handle the response in onload
event from its parent page.
Using XMLHTTPRequest
, aka AJAX
. Since AJAX is request-response type of thing, regardless of the response header, i.e. Content-disposition: attachment; filename=fname.ext
will not work like expected, which is a pop-open a window and prompt user to download as file. Instead, AJAX will store the response in its response
filed rather than treat it as a file.
(AJAX developed to provide no refresh page experience)
Browser can be implemented differently to handle, but that will defeat the purpose of AJAX, thus browsers just store it in its memory.
So, how do we handle that chunk of memory and get it out as file? Introducing Blob
After we get the response from server, we can construct a Blob file and invoke the browser to download, of course, Blob is not all supported yet by the time of written May, 2015.
By the way, FileSaver.js library does a good job to provide cross browser functionality.
Thus, without providing a direct download link with href
, we can download
file using above methods. I personally will recommend to use AJAX, because of its seamless user experience.
Reference:
- https://stackoverflow.com/a/16086435
- https://stackoverflow.com/a/14683228
- http://www.w3.org/TR/html401/interact/forms.html#h-17.13.1