Detecting the File Download Dialog in the browser

Source: Internet
Author: User

In the web application I work on we sometimes need to create PDF documents based on some user input. in most cases, these documents are fairly simple and quick to create, allowing us to create the documents in memory and then send them back to the requesting user with a "Content Disposition: attachment "in the HTTP response. this causes the browser File Download mechanisms to kick in allowing the user to save or open the resulting PDF. this approach works great and I think has come to be the expected behavior for getting files in 3rd party formats (Word, Excel, Adobe PDF, etc .) from a web application.

Generating a file, however, can sometimes take a few seconds. this short duration is not necessarily long enough to justify offloading the file generation to a separate process (e.g. A service bus, a separate worker thread within your Web server process, etc .) butIsLong enough that the user waiting for the download may think that nothing is happening and attempt to click the "Create File" button again. we definitely do not want the user submitting a request to create the same file over and over again, so we might use something like the jquery block UI plug-in to display a "please wait" message and prevent further requests from being made from that browser. this works great, But you eventually need to un-block the UI so that your users can continue doing their work after downloading the file. unfortunately, I don't know of any way JavaScript tricks to detect when the file download dialog is displayed to the user. without being able to hook in to that event, the UI will remain blocked forever, forcing the user to either close and re-open their browser or hit the back button to get away from the "Please wait" message. you cocould use some kind of time out to automatically un-block the page, but in most cases you 'd likely end up un-blocking too early or too late.

There are some ways to work around this by writing the file to disk or some caching mechanisms and then providing a separate URL endpoint to download the finished file, but these approaches require what is, in my opinion, a non-trivial amount of server side code to accomplish. all I really want is a way to let the user know that we're building their file and to keep them from hitting 'submit 'multiple times. in seraching for this I discovered a question on Stack Overflow (originally found on another not-to-be-named site that scraped stackoverflow.com) where one of the answers presented an interesting idea for solving this problem. while we can't use JavaScript to determine when the browser has es a response with the "content-Disposition: attachment" header, we can use JavaScript to determine when the browser has es a cookie with a certain name and value. we can add a very minimal amount of code to our server side implementation to add a cookie to the file download response and then use JavaScript to equate the presence of that cookie with the fact that the file is available for download. let's take a look at some code:

The client side setup

The code I'm showing here is adapted from an ASP. net web forms application, but I'll try to keep it as a generic looking as possible as this approach shoshould work regardless of the platform you use. first, let's see a simple HTML form that we might use to capture the needed input from the user to create our PDF file:

<form id="create_pdf_form">  <fieldset>    <legend>Create Customer Info Sheet PDF</legend>        <div>          <label id="first_name_prompt_id" for="first_name_input_id">First Name</label>          <input name="first_name_input" id="first_name_input_id"/>       </div>        <div>          <label id="last_name_prompt_id" for="last_name_input_id">Last Name</label>          <input name="last_name_input" id="last_name_input_id"/>       </div>      <input type="hidden" id="download_token_value_id"/>      <input type="submit" value="Create File"/></fieldset></form>

Notice the 'did' input field I have ded in that form. we'll use that field to provide a token value to be encoded in a cookie in the file download response. now let's look at the jquery code that we'll use when this form is initially submitted. note that this requires jquery 1.4.2, The jquery block UI plug-in, and the jquery cookies plug-in.

  $(document).ready(function () {    $('#create_pdf_form').submit(function () {      blockUIForDownload();    });  });  var fileDownloadCheckTimer;  function blockUIForDownload() {    var token = new Date().getTime(); //use the current timestamp as the token value    $('#download_token_value_id').val(token);    $.blockUI();    fileDownloadCheckTimer = window.setInterval(function () {      var cookieValue = $.cookie('fileDownloadToken');      if (cookieValue == token)       finishDownload();    }, 1000);  }

First, we're using jquery to hook into the 'submit 'event of the HTML form. this will get fired just prior to the form data being submitted to the server. when this happens we're re generating a token value using the current timestamp. this token can really be any arbitrary string value, but we do want to try and make it unique per request coming from the same browser, and using the timestamp is a pretty easy way to do this. we take that token and add it to the form within that hidden field that we created. this will ensure that the token value gets submitted up to the server (more on this later ).

Next, we're re using the jquery block UI plug-in to block the user from submitting the form multiple times. the behavior of the block UI plug-in is very writable able and I encourage you to go check out the documentation for details on all of the different ways you can customize what message is displayed to the user while the UI is blocked.

With the UI provided tively blocked, we use the 'window. setinterval 'function to create an interval timer. the first argument provided is the function that you want to have executed at each interval and the second argument is how long you want the interval to be in milliseconds. for our purposes we want some code to check for the presence of a cookie value every 1 second. we're re using the jquery cookies plug-in to examine the value of a cookie named 'filedownloadtoken '. when the value of that cookie matches the token value that we generated before (based on the current timestamp), We're going to invoke a method called 'finishdownload '. we'll look at the finishdownload method in a bit. first, let's see what we need to do on the server side.

The server side setup

Again, I 've adapted this example from an ASP. net web forms application, so the code below is C #, but this approach shoshould work for just about any web platform. I 've taken out the participating ARS around how the file to be downloaded is actually created and written to the HTTP response, as that will vary from application to application.

var response = HttpContext.Current.Response;response.Clear();response.AppendCookie(new HttpCookie("fileDownloadToken", downloadTokenValue); //downloadTokenValue will have been provided in the form submit via the hidden input fieldresponse.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", desiredFileName)); //desiredFileName will be whatever the resutling file name should be when downloaded//Code to generate file and write file contents to responseresponse.Flush();

What I like best about this approach is that you were going to have to write 99% of the above Code one way or another. the only addition that had to be made to the server side functionality was the single line where we add the File Download token cookie to the response. this is the cookie value that our JavaScript timer is polling for back on the browser while all of the server side code is building the file to be downloaded. once the response is flushed back to the client, our timer will see that the cookie is present and invoke the 'finishdownload' method. let's take a look at that.

Finishing up on the client side

Once the expected cookie value appears, all that's left to do is a little bit of Clean Up In The 'finishdownload' function:

function finishDownload() { window.clearInterval(fileDownloadCheckTimer); $.cookie('fileDownloadToken', null); //clears this cookie value $.unblockUI();}

All we're doing here is clearing out the previusly set interval timer, removing the cookie, and unblocking the UI so that the user can continue doing their work after they decide what to do with the downloaded file. all in all, we added a line or two to the server side code and a few lines of JavaScript to accomplish our goal of informing the user that we're working on their file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.