Posts
48
Comments
143
Trackbacks
0
Detecting the File Download Dialog In the Browser

Updated 2011-01-28 to reference the correct question stackoverflow.com

Updated 2011-10-02 With a link to a sample application on github.

Updated 2013-07-01 with corrected jQuery Cookie plug-in link and syntax

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 mechanism 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.) but is long 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 could 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 mechanism 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 receives a response with the “content-disposition: attachment” header, we can use javascript to determine when the browser receives 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 should 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 ‘hidden’ input field I included in that form. We’ll use that field to provide a token value to be included 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 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 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 configurable 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 effectively 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 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 should work for just about any web platform. I’ve taken out the particulars 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 field response.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 response response.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); $.removeCookie('fileDownloadToken'); //clears this cookie value $.unblockUI(); }
All we’re doing here is clearing out the previously 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.

I’ve put together a full working sample of this approach in the form of an ASP .NET MVC 3 application that you check out on github: https://github.com/appakz/Detect-Browser-File-Download-Dialog-Sample

posted on Thursday, October 28, 2010 4:38 PM Print
Comments
Gravatar
# re: Detecting the File Download Dialog In the Browser
Brian
11/3/2010 9:34 AM
This solution is perfect! Works great with Spring MVC and a JSP. Thank you!
Gravatar
# re: Detecting the File Download Dialog In the Browser
pietro
11/16/2010 9:00 AM
Nice, thank you very much, but doesn't work on ie6 for me.. IE8, FF, opera, chrome are good, but old ie6 not :-(
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
11/17/2010 10:58 AM
@pietro: What is the issue you're seeing in IE 6? I've tested this out in IE 6 before and have had no problems with it. Drop me a line on the contact form of the blog and maybe I can help you.
http://geekswithblogs.net/GruffCode/contact.aspx
Gravatar
# re: Detecting the File Download Dialog In the Browser
pietro
11/18/2010 7:21 AM
All is OK now.
I applied your demo program to my java program. So I set header, cookie...
You have response.Flush();
I was sending the file using OutputStream, so I didn't do this step. But it wasn't function in IE6.
So I tried response.flushBuffer(); in java and finally it works.
Thanks for great demo program Jesse ;-)
Gravatar
# re: Detecting the File Download Dialog In the Browser
Yuva
12/28/2010 12:07 AM
Hi Pietro,

Glad that you are able to do it for java, can you pl share that code for java. Thanks

yuva
Gravatar
# re: Detecting the File Download Dialog In the Browser
Lakshmi Narayanan
12/28/2010 4:51 AM
Can this be achieved without the use of JQuery?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
1/2/2011 8:44 PM
@Lakshmi: This same technique can be accomplished without jQuery, though you would end up having to write a lot more client-side code to make it work (unless you were using some other javascript library). I know and like jQuery, so that's what I used.
Gravatar
# re: Detecting the File Download Dialog In the Browser
DevFox
1/26/2011 2:52 PM
This was a huge help! Thank you so much!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Didier
1/28/2011 10:55 AM
Thank you for this very elegant solution!

However you reference a question from eFreedom which is wrong: this site only plagiarize stackoverflow.com and messes all search engines results. As indicated on eFreedom, this question is copied from
http://stackoverflow.com/questions/3055138/can-you-use-javascript-to-detect-a-file-download-window-created-server-side

p.s. : the comment form does not accept my email address since it has a “+” in it :(
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
1/28/2011 11:03 AM
@Didier: Thanks for pointing me to the correct question on Stack Overflow. I've updated the post to reflect that. When I first published this I didn't know what eFreedom was, and didn't know any better. I'm glad to give proper credit to the site that actually contained the original question.
Gravatar
# re: Detecting the File Download Dialog In the Browser
dmans
2/3/2011 10:11 AM
You rock! One other cool thing is that the cookie is available in ALL browser windows referencing the same domain/path, so you can monitor the presence of the cookie in the "main" window, but load the d/l into a separate window (which could be nice depending on your needs).
Gravatar
# re: Detecting the File Download Dialog In the Browser
Salman
2/21/2011 12:16 PM
This is a very nice solution. I was searching for this for some time until I found it. BTW, I am also using jQuery and blockUI on the client side, the server side is spring MVC. Thanks for sharing this with everybody.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Gary
3/10/2011 1:12 PM
This is beautiful, thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Mo
3/21/2011 12:16 AM
You beauty! Simple and elegant solution. Thanks so much.
Gravatar
# re: Detecting the File Download Dialog In the Browser
zhonghui
4/19/2011 5:11 AM
very nice,hope this can help me.thanks for your great work,man.

can i add you on facebook:

my is : ZhongHui Duan
Gravatar
# re: Detecting the File Download Dialog In the Browser
cja
4/27/2011 4:02 AM
This is great code - thank you!

For the php users out there, the php equivalent of

AppendCookie(new HttpCookie("fileDownloadToken", downloadTokenValue);

in php is:

setcookie ("fileDownloadToken", $downloadTokenValue);

CJA
Gravatar
# re: Detecting the File Download Dialog In the Browser
TAmes
4/27/2011 11:43 AM
What a great idea. This worked out perfectly for what I wanted to do. Thanks for sharing this technique.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Adil
5/6/2011 9:42 AM
Thanks... this was a great post... i have been struggling for this sort of solution. Thanks a lot for sharing.

for those who are facing issue in reading cookie...

Set cookie.HttpOnly = false

Gravatar
# re: Detecting the File Download Dialog In the Browser
paolosca
6/4/2011 1:06 PM
Hi, I just come across your post, it's brilliant.
Until now I've been using the window.onblur event to detect when the download dialog appears and hide the "please wait" div. I works fine provided the user don't decide to read an email during the wait.
I will definitely try your solution, thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Yuriy Shikhanovich
7/14/2011 4:37 PM
Perfect solution. Adapted it to Java w/out any issues.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Phani Kumar
7/27/2011 12:30 PM
Works Perfect. Thanks a lot
Gravatar
# re: Detecting the File Download Dialog In the Browser
srinivas
7/30/2011 4:23 PM
I have a ajaxForm , when the user submits the page it hits the sever url and necessary page gets generated. But with the example that you have shown here how do I open a pop up window for the incoming file to download.

Can you please provide an example how to achieve it.

My way of sending and opening popup is $('#reportForm').ajaxForm( {

dataType :'json',
type :'POST',
url : 'report/initialRequest.html',
beforeSubmit :validateSearchField,
ifModified : true,
success :function(data, textStatus, jqXHR){},
complete : function(jqXHR, textStatus) {
window.location.href = "report/initialRequest.html" + "?" + $('#reportForm').formSerialize();
$.unblockUI();
return false;
}
});

But in this case what happens its send in another request again and reprocess what it has done earlier.

Can you please help me on this?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Blake
8/10/2011 11:53 PM
What a brilliant hack. :) The only browser I was able to get working without this trick was IE9 using document.readyState. Doesn't work so much with Chrome/FireFox.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Pete
8/12/2011 7:03 AM
Nice one. I was looking for exactly this. Thanks very much.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Mohammad
8/18/2011 10:09 AM
That's awesome! Exactly what I was looking for.
Thank you very much for sharing this.

Gravatar
# re: Detecting the File Download Dialog In the Browser
Marta Ramirez
8/18/2011 12:32 PM
Hi, I'd like to have the Java-JSP translation if possible. I tried to translate but it's not working for me. Thank you.
Gravatar
# re: Detecting the File Download Dialog In the Browser
BethW
9/1/2011 8:42 AM
You are my hero. I have been struggling with this issue for months! Thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Vlad
9/2/2011 6:13 PM
Brilliant! This is exactly what I needed. Thanks a bunch!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Wu Huajie
9/5/2011 6:22 AM
There seems to be a problem On safari for this solution. No cookie is written.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Paul J
9/15/2011 2:12 PM
I'm in total debt to you. I've been trying to get a simple, minimal method of doing this forever! thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
strive
9/17/2011 2:08 AM
i have a similar problem, in my case , i have a small zip file say of 400-500 bytes generated on air and passed on to browser for download which opens up download popup, by this time backend already had updated with file consumption from client, now delimma is when users clicks cancel,i wish to let backend rollback my changes, how can this be achieved. i am sick of this issue kindly help.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Srinivas
9/24/2011 11:01 AM
You saved my life... :-)
Gravatar
# re: Detecting the File Download Dialog In the Browser
Enrique Andreu
9/29/2011 9:07 AM
This solution works me fine in Chrome and FF, but I have a problem with IE9 (IE in general). When the response with the file comes it contains a set-cookie header with the proper value, but when I read the cookie with the jquery function it doesn't read the proper value (it reads the value of the cookie I set when I load the page to test that I'm readingg the cookie properly). It seems like the browser is not setting the cookie due to is a file download response, if i reload the page the cookie of the response is not set.

The server language is PHP, but the solution works fine in FF and Chrome.

Any idea?? Thanks in advance.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Ram
10/7/2011 3:31 AM
How to set cookie in asp application and how to read it in jquery?
I have set the cookie in asp like this Response.AddHeader "Set-Cookie", "fileDownloadToken=something;path = /;"

But Jquery is not reading this.

I am using IE 6.0.Please help me.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Shih-gian Lee
10/17/2011 3:09 PM
It works perfectly! Thanks for sharing this great gem!

Cheers,
Lee
Gravatar
# re: Detecting the File Download Dialog In the Browser
herme
10/19/2011 12:50 AM
How genius idea is!
Exactly what I was looking for!
Thank you so much. :D
Gravatar
# re: Detecting the File Download Dialog In the Browser
phil
10/20/2011 12:24 PM
the cookies was written to the client must be after file sending completely?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
10/20/2011 4:46 PM
@phil - I don't think I understand your question. The cookies should be sent to the browser in the same HTTP Response that contains the "data" for the file to be downloaded. In this way the 'block UI' stuff should go away as soon as the file download dialog appears.
Gravatar
# re: Detecting the File Download Dialog In the Browser
phil
10/22/2011 12:50 AM
if the file not send completely(might be paused by the user).will the cookies be sent to the browser?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Phil
10/22/2011 8:53 AM
sorry I misunderstood this post, I thought this solution is used to detect whether file was already download.. but many thanks you share the very good idea.
Gravatar
# re: Detecting the File Download Dialog In the Browser
willie
10/30/2011 5:15 AM
A great post. You said the sample application is adapted from web form version. Can you post or email me the web form version. I have a project still in ASP.NET 2.0. A lot of efforts is required to migrate to MVC. Thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
fattynoparents
11/17/2011 1:23 AM
man, you saved my life! i spent two freakin' days on this, and your solution works perfectly. thank you!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Yuri
11/17/2011 8:22 PM
Thanks a lot!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Steve
11/24/2011 12:52 AM
Works great except in IE for PDF files. I was able to open the PDF files before applying this solution, however, after changing the code to the above solution, I am getting 'There was an error opening this document. This file cannot be found.'

Error only occurs in IE for PDF files. Does anyone have a clue?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Gabriele Gaggi
11/24/2011 9:30 AM
You save my life! Thanks!!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Denny Saviant
11/30/2011 12:47 AM
One thing for sure..

YOU SAVED MY LIFE!!

a week of headache gone instantly once i found and adapt your concept to my code..

THANK YOU..

TERIMA KASIH
Gravatar
# re: Detecting the File Download Dialog In the Browser
stv
12/5/2011 1:06 AM
Wow!! good solution ...
But..... this will work only if cookie is enabled. Right?
what if it is an environment where cookies are not enabled?
will the data be passed as url encoded?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
12/5/2011 8:58 AM
@stv

This solution will only work for browsers with cookies enabled.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Duong
12/8/2011 2:12 AM
You save my life hero
Thank you a lot
Great solution!
Gravatar
# re: Detecting the File Download Dialog In the Browser
rspaz16
12/22/2011 12:14 PM
I have been seeking this code for a long time! Great Solution!
Thank you very much

This idea is good for many things!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Tom
1/14/2012 1:37 PM
What a great solution. Thanks.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Randeep Singh
2/22/2012 9:45 AM
This is a brilliant solution, thanks!

One issue with it though in the example solution is the timer keep's running/doing the comparison. So you keep calling the finishDownload() over and over which might not be desirable (in my case, on subsequent 'downloads' my submit button which I was disabling until the file was generated kept getting enabled straight away).

Easily solved by clearing the timer (I used http://stackoverflow.com/a/2133217).

:)
Gravatar
# re: Detecting the File Download Dialog In the Browser
Micha von Vau
3/8/2012 11:10 AM
this solutions rocks. i use it with php. great!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Chris
3/9/2012 2:08 AM
Thanks! This is exactly what I was trying to do, but then didn't differently and now changed it to this better version.
Gravatar
# re: Detecting the File Download Dialog In the Browser
none
4/18/2012 4:35 AM
Excellent ! Still useful these days !
Gravatar
# re: Detecting the File Download Dialog In the Browser
Kevin
4/28/2012 5:43 AM
This solution is perfect! Works great with JSP. Thanks a lot!
Gravatar
# re: Detecting the File Download Dialog In the Browser
suresh
5/9/2012 2:19 PM
Great article. works perfectly in asp.mvc 3
Gravatar
# re: Detecting the File Download Dialog In the Browser
dobrobuz
5/18/2012 12:00 PM
Sorry, but it's doesn't work for me. I need to detect when a file finish download inside a IFRAME.
Always when I read the cookie with jquery, its value is NULL
This is my java code:

response.addCookie(new Cookie("tokenDocumentLoad", token));
response.setContentType("application/vnd.ms-excel");
response.setHeader("Cache-Control","no-store");

response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
response.addHeader("Pragma", "public");
response.addHeader("Cache-Control", "max-age=0");
response.setDateHeader("Expires", (System.currentTimeMillis() + new Integer(getServletContext().getInitParameter("webAppResponseExpire")).intValue()));
ServletOutputStream servletOutputStream = response.getOutputStream();

fileContent....

servletOutputStream.flush();
servletOutputStream.close();
-------------------
This is the javascript code:

var cookieValue = $.cookie('tokenDocumentLoad');
alert("cookieValue:" + cookieValue);

Gravatar
# re: Detecting the File Download Dialog In the Browser
Rafael Sisto
5/31/2012 3:16 PM
Hi! Great post!
I had to add the 'name' attribute to the hidden field in order for this to work. Otherwise, the browser didn't send the parameter (maybe it had to do with the form issuing a GET request)
<input type="hidden" id="download_token_value_id" name="download_token_value_id"/>

Regards!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Ahmet
6/19/2012 8:13 AM
Your article helped me a lot. I appreciate your efforts.
Thank you very much.
Gravatar
# re: Detecting the File Download Dialog In the Browser
zu
6/26/2012 2:01 AM
thank you so much for this post - saved me a lot of time! This is the only solution that worked first time, every time! Used with PHP Yii.

may you live long and prosper!!
Gravatar
# re: Detecting the File Download Dialog In the Browser
From BRazil
8/21/2012 8:34 AM
Thanks Jesse!
Gravatar
# re: Detecting the File Download Dialog In the Browser
jobs
9/8/2012 10:34 AM
what if user has disabled the cookie.
Will this work
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
9/10/2012 9:33 AM
@jobs: This approach will only work if the user's browser accepts cookies.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Mark Blackwell
9/16/2012 10:10 PM
great post.

one little hitch that took a while to fix: I needed to set the path variable on the cookie to '/'. without this, the jQuery doesn't find the cookie because it is referenced to the path of the download link, rather than the path of the current page.

dunno if this makes sense or not... i found this only after a few hours of trial and error and I'm still learning some of the web protocol stuff by trial and (lots of) error.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Richard Kuhn
11/27/2012 1:37 PM
Very elegant solution I love it. Thanks for the MVC3 example on Github, I do everything in MVC so it was easy to implement.

@Mark Blackwell and others
I ran into that as well. The thing to keep in mind is it might not always be / (root) dependent on the language you use to create the cookie. For .net HttpCookie defaults to root so you just need to send the null value to root
$.cookie('ExcelDownloadToken', null, { path: '/' });

It sounds like you got it working but figured it worth a mention for others since this is obviously the best solution for cookie enabled browser sessions.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Marc W
12/12/2012 3:16 PM
Thanks so much for this post. It is genius and solves my exact issue.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Rusty D
12/16/2012 10:16 PM
This works great except for one thing. If the modal is displayed and the user hits the stop button or presses escape, this effectively cancels the download, and the modal never goes away. How can I get around that?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
12/17/2012 9:02 AM
@Rusty D: That's a good point and a weakness of this approach. I'm not sure if there's a way that you could detect the fact that the user hit the stop button, though you might be able to detect whether or not they have hit 'esc'. If I have time I'll look into that and see if there might a workaround.
Gravatar
# re: Detecting the File Download Dialog In the Browser
kevin
1/11/2013 5:25 PM
Hm... this looks not working with IE9. Anybody found a solution for it?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Ravi
1/16/2013 5:23 AM
Thanks mate. I cant say how immensely your post helped me.
Gravatar
# re: Detecting the File Download Dialog In the Browser
kevin
1/18/2013 1:02 AM
Please help me PHP guys. I setup a cookie in PHP and then try to read from client(jquery) but it just said something like "token = object object". Client read from with jqeury and setCookie in PHP... is this really working?
Gravatar
# re: Detecting the File Download Dialog In the Browser
naveen
2/13/2013 1:45 AM
Thanks for this.But in IE8 it's not working perfectly.when the download popup comes , the loading state is not getting hidden.it is getting hidden only when i cancel or save the download.it works perfectly for all other browsers. plz help me here
Gravatar
# re: Detecting the File Download Dialog In the Browser
Michael
2/20/2013 11:02 PM
Your a genius! Thanks so much for sharing this
Gravatar
# Thanks!
Chris Valdivia
4/11/2013 11:19 AM
Just echoing what many have already said - great solution, many thanks.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Bartosz Zawistowski
5/27/2013 5:51 AM
Thanks a lot! It's a really nice solution and it's exactly what I needed :)
Gravatar
# re: Detecting the File Download Dialog In the Browser
Valters
6/26/2013 4:47 AM
Thanks a lot! Good solution.. Just one comment. Running my project with debug, that row $.cookie('fileDownloadToken', null); works great, but when project is published, that row isnt working as expected.. I replaced this previous row with $.removeCookie('fileDownloadToken'), and now all works great... Thanks again.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Daren
7/1/2013 4:53 AM
Thanks for this! I had the same problem as Valters. When you click the create file button a second time it wasn't working. Replacing the line $.cookie('fileDownloadToken', null); with $.removeCookie('fileDownloadToken') works fine for me now, no matter how many times I click create download! Thanks Valters!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Jesse
7/1/2013 9:34 AM
@Daren and @Valters: Thanks for pointing that out. I guess the syntax of that plug-in has changed since I wrote this post initially. I've updated the post accordingly.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Big Barn Owl
10/11/2013 3:58 PM
Thank you very much for this! It's an elegant,classy solution. Just what we were looking for. I have it working with a ColdFusion site and it was easy to implement.
Gravatar
# Thanks
Ryan J
11/6/2013 11:06 AM
I just wanted to say thank you for this example - it helped me greatly. Thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Shyam
11/20/2013 8:02 PM
Bull's eye! I have been looking for a solution for exactly the same problem and my colleague stumbled upon this blog! Thank you!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Suba
12/6/2013 3:08 PM
Thank you so much. It saved my day.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Basil
1/27/2014 8:58 AM
Thanks, this is really useful. Works on WinForms 3.5 also.
Gravatar
# re: Detecting the File Download Dialog In the Browser
MGF
1/31/2014 11:07 AM
I'm struggling to get this working in my implementation and wonder if anyone can see why.
The 'Please Wait' is displayed but the cookie is never matched and so the screen remains showing 'Please Wait' forever. I've tried returning a response from the Server side instead of 'void' but this never works either.

I've simplified the code as there's a lot of detail in the original but basically I generate an Excel file which contains an image and some data then download this (all of which works). All I'm missing is being able to clear the 'Please Wait'.

The user clicks on btnGraphExportToExcel to start things off.....

-----------
CLIENT SIDE
-----------

<div>
<br />

<span>Download What If</span>

</div>


function ExportGraph(){
var url = '@Url.Action("GraphExportToExcel", "ExcelHelper", new RouteValueDictionary(new { fileURL = "PARAM1", mstartDate = "PARAM2", mendDate = "PARAM3", period = "PARAM4" }))';
// These values are all defined elsewhere
url = url.replace("PARAM1", imageName);
url = url.replace("PARAM2", startDate);
url = url.replace("PARAM3", endDate);
url = url.replace("PARAM4", _display_period);
url = url.replace(/&amp;/g, "&");
myLink = url;

loadMyLink(imageName);
}

function loadMyLink(imageName) {
$.blockUI();
window.location.href = myLink;

fileDownloadCheckTimer = window.setInterval(function () {
var cookieValue = $.cookie('fileDownloadToken');
if (cookieValue == imageName) {
finishDownload();
}
}, 1000);
}

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

------------------------------------------------------------
SERVER SIDE (ExcelHelperController.cs -> GraphExportToExcel)
------------------------------------------------------------

public void GraphExportToExcel(string fileURL, string mstartDate, string mendDate, string period)
{
// Create a spreadsheet and populate it with the required data
// ALL THIS WORKS AS EXPECTED

// Provide the download dialog for the file
string folderPath = ConfigurationManager.AppSettings["ExcelFolderPath"] + "/" + Guid.NewGuid();
string serverExcelFilePath = Request.MapPath("~" + folderPath + "/");

string dateStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
string excelPath = serverExcelFilePath + "ExcelHelper_" + dateStamp + ".xlsx";
MakeFileDownloadable(excelPath, fileURL);

// Delete the image from the server
DeleteImageFileFromServer(fileURL);

// Delete the Excel file from the server - THIS MUST BE DONE AFTER THE FILE HAS BEEN DOWNLOADED
DeleteExcelStore(folderPath);
}

private void MakeFileDownloadable(string fileName, string imageName)
{
Response.Clear();
// Add a cookie with the imageName in it so we know we've downloaded the file contain
Response.AppendCookie(new HttpCookie("fileDownloadToken", imageName));

Response.ContentType = "application/vnd.ms-excel";
string fullFileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
Response.AddHeader("content-disposition", "attachment; filename=" + fullFileName);

using (FileStream sourceFile = new FileStream(fileName, FileMode.Open))
{
long FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, getContent.Length);

using (Stream outputStream = Response.OutputStream)
{
outputStream.Write(getContent, 0, getContent.Length);
}
}
Response.Flush();
Response.End();
}
Gravatar
# re: Detecting the File Download Dialog In the Browser
amelie
2/12/2014 4:31 PM
Great solution! Thank you! but what happens if the cookies are disabled on the client's browser?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Marcos Casal
3/4/2014 4:17 AM
It works fine. I had a problem in IE with my spring mvc application because I didn't set the path of the cookie and it is set by default to the current document location. In the call to the method who exports the file the document location has changed and the read of the cookie returns undefined ( $.cookie("fileDownloadToken"); ) . I solve this problem setting the root path in the cookie before add it to the response header ( cookie.setPath("/"); )
Gravatar
# re: Detecting the File Download Dialog In the Browser
Edmund
3/24/2014 11:28 AM
Works Awesome! All I needed was the jquery "polling" part and adapted the rest to my page.
I actually call an iFrame and in the C# if(!postback) set a cookie called "isLoading" = true; and start the jquery looping/checking code.
All the jquery does is check to see if the cookie= false.
Then I purposely do a postback and in the response set the isLoading cookie to "false";

When jquery sees false, continue with whatever javascript I need to do! (Like redirect, or load a popup etc etc.)

Thanks!
Gravatar
# re: Detecting the File Download Dialog In the Browser
Liviu
4/6/2014 1:23 PM
Thank you
Gravatar
# re: Detecting the File Download Dialog In the Browser
SD
4/11/2014 11:57 AM
Great solution! Thanks so much for posting this.
Gravatar
# re: Detecting the File Download Dialog In the Browser
Dragos
5/19/2014 11:38 AM
Exctly what I was looking for.
Good job!+
Gravatar
# re: Detecting the File Download Dialog In the Browser
Sujin
6/12/2014 10:13 AM
Thank you so much Buddy !!! You just nailed it out. I was scratching my head all the day for this...
Gravatar
# re: Detecting the File Download Dialog In the Browser
Peter
6/25/2014 5:39 PM
Please let me know how to create the value in java for 'downloadTokenValue' before adding it to the cookie?
Gravatar
# re: Detecting the File Download Dialog In the Browser
Nipuna
7/13/2014 11:20 AM
Thank u so much ..its really helpful for me

Post Comment

Title *
Name *
Email
Comment *  
 
Meta
Tag Cloud