Skip to content Skip to sidebar Skip to footer

Ajax File Download Issue

I am downloading a dynamic file in my application, simulating ajax using iframes. What I am doing is, when the download request is made, I will create a dynamic invisible iframe, a

Solution 1:

I created the jQuery File Download plugin (Demo) which also fixes the problem and provides some other nice features. It basically gives you a "full Ajax-like" experience for file downloads (complete with callbacks even) that isn't normally possible for file downloads. It works pretty similarly to some other answers with an iframe but has some cool features that I have found quite handy:

  • User never leaves the same page they initiated a file download from whether it is successful or there is an error
  • successCallback and failCallback functions allow for you to be explicit about what the UI behavior is in either situation
  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Solution 2:

Solution 3:

You should start a timer in the client when the download request is made which tests the state of the iframe at a specified interval:

if ( ( iframe.document && iframe.document.readyState == 'complete' )
    || iframe.contentDocument )
{
    stopTimer();
    closePopupDialog();
}

Solution 4:

Solution 5:

You can use a flash download manager - google will reveal a slew of them.

Your other option is to use real AJAX. Simply make a request to the download URI, and when you get your response, use the responseBody instead of the responseText attribute of the XMLHTTPRequest object.

You'll need a way to write that to the harddrive, which can be done in IE with lax security constraints and the ActiveXObject "Scripting.FileSystemObject" You might be able to use the data uri approach: http://en.wikipedia.org/wiki/Data_URI_scheme with a base64 encoding, but I'm not sure if that will work.

Otherwise you're back to flash to write the data you downloaded via ajax to disk.

If you know the size of the dynamic download and exact timing isn't required in the specification, then you could do an internet speed check before the download, add some buffer time to the calculated time it will take to download the file, and just show the dialog box for that given period of time. Very hackish, but then again this scheme seems a little marketing-requires-it-to-be-so-it-shall-be

Post a Comment for "Ajax File Download Issue"