How To Detect Download Complete In Javascript
I want to execute two operations in one javaScript function force download of a csv file send an ajax request to mark records in table that records were downloaded. Since both of
Solution 1:
I have implemented such a mechanism in a web application with the following workflow:
- the user selects a file on their computer
- they configure options of the app
- they click the submit button
- a loader starts animating client-side
- the browser send the entire form to the server for processing
- the processing (which is actually about converting a guitar score to a tablature) yields a text/plain file, which is stored on the server (but not sent yet): a small JSON with the link to the generated file is sent back. That JSON data represents either success or error. In the case of error, the message is displayed to the user. In the case of success, the status field is set to
OK
and the payload contains the link to the file. - the JS code handling the AJAX call, upon success, triggers the download.
- the browser presents the user with the usual (e.g. in Firefox) "open or save file" dialog
- the web app detects the opening of the dialog and hides the loader.
It seems pretty similar to your need.
The gist of the solution is this:
- triggering the file download is done by setting the
src
attribute of aniframe
hidden in the page - the server sends a cookie in response to the request for the file to be downloaded
- a JS code on a timer inspects the cookies of the document (which, very fortunately, includes the cookies to the iframe) and upon seeing "the Holy cookie", knows for sure that the file download has started, which is the only event the code can grab.
Quickly looking through the PHP code of my web app, I see this:
// This cookie is for the jQuery.fileDownload pluginheader('Set-Cookie: fileDownload=true; path=/');
You have the name of the JS code that does the last bullet point item in the code comment :-) Another reason among the myriad of reasons why I write commented code...
HTH.
Post a Comment for "How To Detect Download Complete In Javascript"