-4

Given two codes, both trying to trigger server to give back of downloadable file using http header in response i.e. "Content-Disposition", "attachment; filename=filename.ext:

  1. Using form, $('<form></form>').attr('href', path) ... .submit().remove();

  2. Using ajax, $.ajax(url, config);

I would like to know why browsers handle that differently, since form and ajax are not quite different in term of sending request and receiving servers responses. I have search around, but nothing is convincing.

PS: I'm aware of CROS, but in this case cross domain is not an issue here.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Alan Dong
  • 3,981
  • 38
  • 35

2 Answers2

1

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,

  1. 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.

  2. 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.

  3. 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:

  1. https://stackoverflow.com/a/16086435
  2. https://stackoverflow.com/a/14683228
  3. http://www.w3.org/TR/html401/interact/forms.html#h-17.13.1
Community
  • 1
  • 1
Alan Dong
  • 3,981
  • 38
  • 35
0

The whole point of AJAX is to return the response to your SJ code.

That's exactly the opposite of downloading a file, which serves the response to the user.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964