Sunday, March 11, 2012

File download indicator in browser

For last few days I have been struggling with a requirement to show file download indicator. Here's the requirement.

Web page has a link "Download File". On click of this link - a JSON post request is sent to the server. The server generates the files based on the JSON input and streams back with Content-Disposition "attachment" for the browser to download. There are several ways to visually indicate the click of the link:
  • Normal form post - Create a dynamic form and post it. On the server-side make sure content disposition is set to attachment. When browser receives the response, it pops the "Open-Save-Cancel" dialogue box. 
           Cons:
               - No control of the page response time, page dies in case of timeouts
               - Page refreshes and the current context of the user is lost
  • Ajax post - Do an Ajax form post with JSON data. Download "waiting" indicator can be easily initiated with "Ajax prefilter". In the response from the server send back the URL to download. Remove the "waiting" indicator. Change the window location to the URL and let the browser do the rest. 
           Cons:
               - Retain the file on the server and run a background cleanup
  • Iframe post (recommended solution) - Create a dynamic form and post (target of the form) it to an iframe. Disable the download link, show the "waiting" indicator. Start the timer and look for presence of a cookie. If the cookie is found, remove the indicator and enable the link. This requires some server side code as well: adding the cookie. The detailed sample code:
          
          
          The client side code: 
          
       
         The server-side code:
         
       
           Cons:
               - Server has to set an extra cookie

The third approach has helped in solving for the following:
1. Submit a JSON request to the server
2. Show/Hide a "waiting" indicator
3. Controlling the timeouts and indicate the user of delays (if any)
4. File download handle

Let me know if there are other ways of making it work.

No comments: