AJAX, file downloads, and IFRAMEs
AJAX, ASP.NET, UI By Dave Ward. Updated March 10, 2012
“Click here to download this report in Excel (CSV) format.”
We’ve probably all implemented this functionality in ASP.NET applications at least several times. Any time you’re dealing with report data, it’s expected that the data be available for download. Unfortunately, AJAX makes this somewhat difficult. Since there is no traditional HTTP response, you have no context with which to send the file to the browser for normal download.
Enter inline frames (IFRAME). Probably one of the most under utilized HTML elements around, dynamically creating an IFRAME allows you to round trip an HTTP request and response without disrupting the AJAX-ness of your async postback. Since any browser that supports XmlHttpRequest supports IFRAMEs, it is as safe to use as AJAX is in the first place. This is a simple example of the technique, using a static list of files in a dropdown, but it could be adapted to more dynamic file creation scenarios easily.
This is the example download page. The JavaScript comments explain how the IFRAME is created and directed to the GenerateFile.aspx:
<html> <body> <form id="form1" runat="server"> <asp:ScriptManager runat="server" /> <script type="text/javascript"> // Get a PageRequestManager reference. var prm = Sys.WebForms.PageRequestManager.getInstance(); // Hook the _initializeRequest event and add our own handler. prm.add_initializeRequest(InitializeRequest); function InitializeRequest(sender, args) { // Check to be sure this async postback is actually // requesting the file download. if (sender._postBackSettings.sourceElement.id == "DownloadFile") { // Create an IFRAME. var iframe = document.createElement("iframe"); // Get the desired region from the dropdown. var region = $get("Region").value; // Point the IFRAME to GenerateFile, with the // desired region as a querystring argument. iframe.src = "GenerateFile.aspx?region=" + region; // This makes the IFRAME invisible to the user. iframe.style.display = "none"; // Add the IFRAME to the page. This will trigger // a request to GenerateFile now. document.body.appendChild(iframe); } } </script> <asp:UpdatePanel runat="server"> <ContentTemplate> <asp:DropDownList runat="server" ID="Region"> <asp:ListItem Value="N">North Region</asp:ListItem> <asp:ListItem Value="W">West Region</asp:ListItem> <asp:ListItem Value="SE">Southeast Region</asp:ListItem> </asp:DropDownList> <asp:Button runat="server" ID="DownloadFile" Text="Generate Report" /> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>
GenerateFile.aspx can be empty, other than the Page directive to wire up the code file. There, you write the file to the response object just the same as you normally would:
protected void Page_Load(object sender, EventArgs e) { string FileResponse; string Region = Request.QueryString["Region"]; // Code here to fill FileResponse with the // appropriate data based on the selected Region. Response.AddHeader("Content-disposition", "attachment; filename=report.csv"); Response.ContentType = "application/octet-stream"; Response.Write(FileResponse); Response.End(); }
Now, when DownloadFile is clicked the file will be sent to the user asynchronously. Easy as that.
Get the source
If you’d like to browse through a complete working example of what’s been covered in this post, take a look at the companion project at GitHub. Or, if you’d like to download the entire project and run it in Visual Studio to see it in action yourself, grab the ZIP archive.
AJAX-File-Download on GitHubAJAX-File-Download.zip
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
3 Mentions Elsewhere
- Tweets that mention AJAX, file downloads, and IFRAMEs | Encosia -- Topsy.com
- Bookmark – AJAX, file downloads, and IFRAMEs | blogsmarter
- ASP.NET: Downloading files from a UNC share | Rui Jarimba



How does this technique hold up if you are running on a secure site?
Will it give you a mixed content message?
That’s a good point, Dave.
If your AJAX front end page is SSL encrypted and the GenerateFile.aspx page was called using clear-text http, that would generate the mixed content warning for your users.
In the example above, the IFRAME should also use SSL as its transport and no error should occur. However, if you had any trouble with it, you could always rewrite line 26 to explicitly point the iframe to the HTTPS URI of your GenerateFile.aspx page and it would work without any modification to GenerateFile.aspx itself.
If do you implement this technique in an SSL environment, I’d be eager to find out how it goes.
Hi, I tried to follow your advice to point the IFrame source directly to a SSL url but I’m still getting the security warning message. Note: the page that adds the IFrame is coming from a SSL page also. Pls help.
To avoid security warnings (with IE) and similar problems on a SSL site you should:
1) only start a file download in response to a user click. Arbitrary downloads (using IFRAME) lead to security warnings.
2) if you want to do a POST request, point the iframe to a blank html URL (do not use “about:blank”) before submitting a with the iframe as target. This means you have to prepare the iframe long before actually doing the download. You can’t use window.setTimeout() to do the POST because of the problem I mentioned above. In my web applications I have a hidden iframe waiting for downloads all the time.
hello! im a very noob programer at asp.net
could you tell me how do i call that script?
Luis, first I should make sure you’re using AJAX. This technique is an unnecessary level of complexity for a regular asp.net page.
If you are using AJAX, the idea is that you replace the middle section of GenerateFile.aspx.cs with your own code to generate the data that you want to send back to the user. Then, you’d add lines 5-36 of the first code listing into your main aspx page to call GenerateFile.
I don’t like this technique because I have to create a new page for all the modules where I want print/download/etc functionality.
I prefer this: partial postback to the server, generate the file in a temporary folder and register a javascript that opens a new window targeting to the temp folder of the website.
It would be easy to create a generic implementation of GenerateFile that used a session variable or database reference to generate downloads for all of the pages in an application.
Aside from adding extra clutter and another step for the user, JavaScript popups on the tail end of partial postbacks will get blocked by the browser if the user is running default popup blocking settings. That’s always a pain.
Small issue is that Firefox and Opera do not support IFrame. Frame is better to use as its standardized DOM.
Better yet, use a DIV with src attribute
IFRAME is supported on FireFox and Opera (FireFox is what I used to test this code). They’re even supported on Lynx. Any browser that has XmlHttpRequest support to run the AJAX framework on also has IFRAME support.
Lets say the DownloadFile button was inside a repeater template, how would you refer to the button on the client side inside the scriptmanager script?
Say the DownloadFile button was in the item template for a repeater called Repeater1. The name of the first row’s button element will be Repeater1_ct100_DownloadFile. The second row’s will be Repeater1_ct101_DownloadFile. And, so on.
I’m assuming you probably have a repeater with buttons on each row that you want to have trigger the download of a different file associated with the row the button is on. In that case, you probably want to use the button’s CommandName and CommandArgument, do something with those in the repeater’s OnItemCommand handler, then create the IFRAME in _endRequest instead of _initializeRequest.
If it were me, I’d probably set each button’s CommandArgument to a primary key, and use that in OnItemCommand to set a session variable. Then, check that in GenerateFile.aspx to determine what data should be generated.
Thank you..
Exactly what i wanted to do.. i would had never thought storing the id for file in session
I’ve been trying to implement this solution. My situation is a little bit different.
My Download buttons are inside rows of a grid. Any ideas on how to hook each button to corresponding filename and have the InitializeRequest work with each button ID.
Please note that each button is inside an update panel which is inside a template column.
While the file downloads does take place…I need a mechanism whereby when the data for the excelsheet is being retrieved[could take a few mins] …I need to inform the user with some msg like “Getting data” in the meantime[This was the real impetus in going for AJAX]
Off the bat, the best way I can think of to do that is to use a technique like my CSS progress indicator for AJAX on beginRequest. Then, in your GenerateFile.aspx’s body.OnLoad, use client script to communicate back to the iframe’s parent to call a JavaScript function that removes the progress indicator (in the same way that my CSS technique’s EndRequest handler does).
Well I did follow the above but the div element changed from the .Progress to .Normal behaviour even before the GenerateFile.aspx call was completed.
You’ll want to remove the EndRequest handler wire-up in my example. For quick example, remove the line “prm.add_endRequest(EndRequest);” and modify the function signature to just EndRequest() (remove the parameters).
Then, in your GenerateFile.aspx, set body.OnLoad to parent.EndRequest().
I believe that should work.
Well I had commented out your EndRequest code but the div element assumees Normal behaviour even before the call to the GenerateFile.aspx is completed.
Ah, what’s happening is the partial postback is completing and then replacing the div’s HTML with server generated HTML (including the “normal” CSS class) almost instantly.
Try using a regular JavaScript call to the function that creates the IFRAME, instead of letting the form submit. Something like OnClick=”InitializeRequest(); return false;”.
When I get a chance, I’ll update the example to add progress indication. That’s a good idea.
When I used the above code snippet OnClick=�InitializeRequest(); return false;� to compile in Visual Studio.Net I get the foll. error
Error 14 ) expected
Error 15 Invalid expression term ‘)’
And when I use the following after removing the parameters from the original request
OnClick=�InitializeRequest()�
Error 14 ‘ASP.callgeneratefile_aspx’ does not contain a definition for ‘InitializeRequest’
Sorry, I meant the client side OnClick. Here’s some code that should help:
Then, you’ll just need to work in a call to parent.EndRequest() from GenerateFile.aspx, when it’s finished generating the file.
The call to the Parent.EndRequest never fires…
PS: I added the alert to see if the script gets fired in an invisible IFrame…it does so I know the function gets called but is not executed because I embedded another alert message within the parent EndRequest but I never get that on the page
alert( ‘This is an ALERT message to the user!’ );
parent.EndRequest();
Try ownerDocument.EndRequest().
After tinkering a lot I found that if you commented the below code then it works with Parent.EndRequest
I guess the Response.Write stops the code being called
// Response.Write(FileResponse);
// Response.End();
That makes sense. The file response stream precludes any HTML in GenerateFile.aspx’s response (including the JavaScript call).
You could have GenerateFile.aspx create and write the file, emit the parent.EndRequest() call as its output, then meta refresh itself to an appropriate URL that sends the file through its response.
That should provide an accurate progress state for the parent page.
Yeah I had initially though of that method bit heard so much of AJAX , I thought might as well give it a try.
Thanks for being with me through all of this
I leave this thought with you
Education teaches you what to do; experience teaches you what not to do :-)
I think there may still be hope, using a different method (directly requesting and receiving the file stream through XmlHttpRequest). I’ll give that some thought and see if I can improve on this in a way that’ll work for your application.
Thanks Dave. I appreciate a lot.
Looking at the amount of data going(in excess of > 65k rows), its over the limit for excel …so now I intend to use Access but I want to zip it and then delete the .mdb file to conserve space.
Is there a way I can commmunicate with the end user that Hey..1. Data is being retrieved…2. being zipped …3. mdb file is being deleted as and when these actionss happen in the above scenario?
Next one is a bit off tangent:
…While I have been able to create and zip the file I cannot delete .mdb it since the associated .ldf it creates exists there..Have you come across such a problem?
You might consider using XML or CSV, instead of Access. They are probably easier to generate and will zip down smaller (and avoid the file locking problems).
As for the .LDB files laying around, that usually indicates that the connection is still open. Make sure to .Close() whatever connections you may have to the Access database, before trying to clean up your temp files.
When I rework this code to provide progress indication, I’ll try to work in provisions for multiple steps of progress, which would be what you need for that 3 step process. I’ll hopefully get to take a look at doing that sometime next week.
The constraint from the end user is that they their skill set is restricted to MS Office products only …so considering the number of rows we are dealing with Access it has to be ..
I have checked it multiple times in debug mode that the OLEDB connection close stmtis executed but I suspect since this being COM interop call on ADOX.dll the connection remains open till the appdomain is refreshed
Take a look at this. It’s a rough proof of concept, but should be adaptable to your progress indication needs:
http://encosia.com/source/FileDownload.zip
Yes it could be so if I need to show zipping and deletion I need to create two more pages and to do chain forwarding from one to another with appropriate Javascript calling the parent scripts informing the user of the present operation.
You could either do it that way, or you could set GenerateFile.aspx up to emit incremental JavaScript progress indication update calls with Response.Writes and only redirect to RetrieveFile.aspx on the last one.
Ok I have got it working and have been doing a few test run…The major thing I notice is that the app takes 100 % CPU usage at times which may impact other apps when deployed to production…I think its due to simultaneous extraction of data from Oracle Reader and an insert into an access DB
Great to hear it’s working for you.
I believe IIS allows you to throttle maximum CPU usage, on a per-site basis. I’d check there, if you have access to the IIS management console where it’s deployed.
Dave…
Now after a months time on production, its time to refactor :-)….I was trying to pass an error parameter for the following snippet in GenerateFile.aspx but it fails where ex is the .net exception object
Response.Write(“parent.ErrorMessage
(‘” + ex.Message +”‘ ); “);
Otherwise without the parameter it works fine
Are you getting a JavaScript error or anything?
Could ex.Message contain ‘ characters that are terminating your JavaScript string early?
Thanks it worked …..the system error message contained the whole lot of special charcters…so did regex to remove them.
Once again, thanks a lot
Cheers,
AC
This is a great solution, and it works fine, as long as my contents of the file is static (I put it in a Session-object).
But I also have to print/download data edited on the screen ( e.g. TextBox ). Is this also possible?
If it’s something you can pass on the QueryString to GenerateFile.aspx, that’s the easiest way to handle dynamic requests.
Otherwise, you can move the JavaScript code from InitializeRequest to EndRequest and then use the partial postback to update your Session object with data from the page’s controls. That way, GenerateFile.aspx could be called after you’ve updated your Session and use the Session data when generating the file.
Excellent!
Thank you very much, you just made my day ;-)
I have another tiny problem. My IE7 browser blocks the download. Is there any way to avoid this? Or a way to configure IE7 without stopping pop-up blocking?
There shouldn’t be any pop-up to block. Using my example, GenerateFile.aspx returns nothing more than a file stream in its response to the iframe’s request.
I found out what causes the problem: when I use the initializeRequest it works fine, but when I use the endRequest, I get the block-message.
Do you have a solution?
Are you purposely trying to open a pop-up window in EndRequest, or is something else happening? The way it works in the example above, only a file stream is returned and pop-up blockers are never involved.
Do you have yours online anywhere I can take a look at in action?
Great Solution Dave!! It was very useful to me.
Thanks
Excellent solution, Dave!
I do have a question for you. I’m having trouble getting GeneratingFile.aspx to do the download when it is inside the IFrame. If I execute the file directly from the browser, it works fine. However, if I load it into the IFrame, nothing happens. The odd part is that I can set a breakpoint for the Page_Load event (which is where the download code resides). The breakpoint hits and all of the download code seems to execute successfully.
Do you have any ideas of things to check?
Thanks!
Are both pages in the same domain? I’ve seen occasional strangeness when opening cross domain iframes.
Other than that, I’d suggest watching both pages with FireBug and make sure something unexpected isn’t happening in the DOM.
Hi, this piece of code helped a lot. But, i have a problem. The GenerateFile.aspx works fine and it emits a excel file (i export a grid), however, the parent page (host page) is posting back even if this button is in the Update Panel. Why is this happening ? (But the beginReq and endReq methods do get fired).
If you don’t have any need for a partial postback, you could just as well use a regular client side onclick handler that calls a JavaScript function. Something like:
<asp:TextBox OnClientClick="GenerateFile(); return false;" />Just move the code in my example’s InitializeRequest handler to a function named GenerateFile (or whatever you want, as long as it matches your onclick).
The “return false;” will prevent the browser from submitting when the button is clicked, and stop any postback from happening.
This is the code snippet I was exactly looking for. I could make the download possible. But after the download happens, the downloaded file contains the source code of the GenerateFile.aspx page(i.e the page that contains the download logic).
For example:
If I download a ‘TextFile.txt’ file with content – “This is a text file”, the downloaded file contains: the above text followed by the source code of GenerateFile.aspx . How do avoid this?
Your help is very much appreciated.
Thanks,
That’s a really strange problem.
Just to double check, you do have ASP.NET enabled on your server, correct?
If you want to email me source that reproduces the problem, I’ll take a look at it.
Dave,
As you suggested, I put the download logic in a code-behind page. I removed all the html markup tags except for the tag. Now the downloads are happening correctly without writing any source code into the downloading files.
Thanks Dave. Thanks a Lot.
This is for general reference:
In the above example, the GenerateFile.aspx should have a code-behind page GenerateFile.aspx.cs which contains the server code. GenerateFile.aspx should contain only tag.
Note: In the previous comment:
“In the above example…” – this is in reference to my first comment in the thread.
Thanks.
There is another question.
I have the following scenario:
1. User click on submit button
2. File generated and sent back to user
3. Page redirected to thankyou.aspx
How to deal with redirection?
Thanks,
Oleg
Unless the file generation takes significant time, I’d suggest showing the thank you message at the beginning of the file generation. Users are used to this anyway, and you can word it like: “Thanks. Your download will start in a second”.
Thanks Dave, but I MUST redirect to another page just after download starts.
In that case, about your only option is this:
- Create the file on the file system (or Session) in GenerateFile.aspx.
- Emit JavaScript that calls parent.document.href to redirect the visible page.
- Emit JavaScript that calls document.href to redirect the iframe’s target to the generated file. This could either be the physical file on the file system or another aspx page that handles delivering it if it’s in the Session.
You can see basically that same idea in action in my progress for long running task post.
Thanks Dave
Hi Dave,
Thanks so much for this article… really helpful.
I have one issue I wanted to ask you about, however. I’ve found that with IE6 and IE7 on XP/SP2, the setting for “Automatic prompting for File Downloads” is “Disable” by default, resulting in the browser blocking the download.
The user is prompted (in the Information Bar) as to whether to download anyway, but even if he chooses “Download File…”, the file is blocked and the page just refreshes. If the user re-initiates the entire process again the file will download fine (at least until the next time he visits the page).
Have you dealt with this issue before? Naturally I’m reluctant to ask my users to change the automatic prompting setting to “Enable”.
You’ll find that to be the case any time you serve the download at the end of a postback (partial or not). To avoid that, you need to create the iframe that generates the download before beginning a server side request (as seen in the example above).
Is this possible if the file being generated is dynamically created by various input fields being posted back. Is there anyway to bypass the download blocker in this case?
I tried creating the iframe before the postback and have the result from the postback include javascript that sets the source of the already existing iFrame but it also gets blocked.
Unfortunately, any XmlHttpRequest or traditional postback before the file stream is served to the browser will always cause it to be treated suspiciously by IE. I’ve tried quite a few ways of circumventing that without any luck.
One working alternative is to set the iframe’s URL with those parameters on the QueryString, and build the file directly.
I downloaded your sample and I encountered a problem where all the scripts injected into the iframe fire at the end of the processing and not after the 0, 25, 40, 90, and 100 % events when using IE6.0. Using Firefox seems to be ok.
This is a great article and i hope to see it working.
I am Having a problem with IE 7, my website is using frames and i want to download a file from one of my inner frame but IE blocks it with its information bar, and when i click download file in it it refreshes the whole page………..
DO anyone have a solution
View Mohit Bansal’s profile
This will happen if the iframe is created after the partial postback. Unfortunately, it’s a browser feature and there is no workaround for it (I’ve tried quite a bit).
If you can find a way to create the iframe before your partial postback (or without a partial postback at all), it won’t happen.
very cool post
Hi How can i display pdf in a iframe when the list of filenames is there in the gridview.upon selecting gridview the pdf displayed in the iframe.
i want to display pdf files in the iframe.this should fired when gridview selected,actually iam getting the files from server.
Can you do the same thing by calling a web service instead of update panel?
Like, you call a web service that returns pdf data and the browser opens the returned pdf data using Adobe Reader.
-Ravi
I have a user control which displays a list of files uploaded in a gridview. The gridview provides a link for every file to the user to download the file. The gridview is inside a updatepanel. Now I can use this user control in a normal web page or a web page opened in a modal dialog. I was trying to use the code for downloading files as discussed above. This code works fine when we are downloading from a normal webpage(not modal window). When I try to use this on a modal window, I am finding an issue which asks me to download the file twice. I am not sure why this is happening. Can some one help me understanding why my InitializeRequest method fires twice. Appreciate any help.
Thanks in advance
Shyamal
Hey, I must be missing something here, but you can achieve this asnc download WITHOUT the clutter of having to use IFRAMES.
For example, lets say you need to download a file by clicking a LinkButton within a row of a GridView control that is within an UpdatePanel.
To do this, all I did was wire up a LinkButton to handle the download when the GridView_Command event fires, then I registered the LinkButtons’ postback event with the ScripManager during the RowDataBound
Thats the theory…here’s some sample code…
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Alternate || e.Row.RowState == DataControlRowState.Normal)) { ScriptManager sm = (ScriptManager )this.Page.Master.FindControl("ScriptManager1"); sm.RegisterPostBackControl((LinkButton)e.Row.FindControl("lbFile")); } }Hope this helps someone…
hi richie,
you just made my day! the code is great!
thanks, evelyn
Brilliant – this worked like a champ. Cheers!
Can you please share the the full code ?
Thanks and regards
Ghygi
I cant run this sample in Opera and Safari.
Iframe is not supported by these browser.
What is the solution?
Those browsers do support iframes. Specifically, any browser that supports ASP.NET AJAX definitely supports iframes.
What specific error are you getting?
In safari, if i click download button,
it downloads the GenerateFile.aspx. i dont n=knoe why?
And in opera, whilw clicking Download button nothing happens.
But this is working fine in IE,Mozilla. My code is as follows:
In Default.aspx i just pasted ur html code.
In GenerateFile.aspx.cs :
FileInfo file = null;
string filename = null;
filename = @”E:\DV\57\187\Media\55\Video\56_Original.flv”;
string[] FileExtensionForDownload = filename.Split(‘.’);
file = new FileInfo(filename);
Response.Clear();
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + “filename.” + FileExtensionForDownload[1]);
Response.AddHeader(“Content-Length”, file.Length.ToString());
Response.ContentType = “application/octet-stream”;
Response.WriteFile(file.FullName);
Response.End();
Can u tell as soon as possible?
I think that might have something to do with the content-type being incorrect for that file type. Try setting it to something like application/x-shockwave-flash.
Hi Dave,
I was going through your sample and it looks great.
However, I found that this example does not work when we try to download MS excel file on IE6. The page simply refreshes but no file download dialog appears(It is working perfectly on IE7).
What could be the reason? I tried hard to find a solution but couldn’t find one. Has it got something to do with browser settings?
Regards,
Praveen
If the page is fully refreshing, that suggests ASP.NET AJAX isn’t working correctly. A JavaScript error in the InitializeRequest handler could cause that.
Hi Dave,
If there were any problems with ASP.NET Ajax then it wouldn’t have worked even on IE7.
But for my case it’s working perfectly on IE7. Problem happens only on IE6 and that too only when I try to download Excel files (This does work with word files).
Any ideas what the issue might be?
Thanks,
Praveen
I just ran the sample in IE6, to double check that it works. I’d say double check that your security settings aren’t causing IE to block the download.
Hi Dave,
Your Blog helps me A LOT! I downloaded the FileDownload.zip and run on IE7. After I clicked the “Generate Report” button, a simple gif animation is displayed for a waiting screen. I noticed that gif animation isn’t animated. Since I have a same problem on my project, do you know how to make gif file animate while a file is generating?
Your help is very much appreciated.
I’m not sure why that would be. The spinner.gif in that zip is definitely animated. If you directly view spinner.gif in IE, does it animate for you?
Hi Dave,
Thank you for your quick response. Yes the spinner.gif animates when I put it on the page. It seems that gif file doesn’t animate if I run the application using VS 2005 built in web server — because the spinner.gif animates when I run it using IIS. Sorry I asked you without enough testing.
Thank you very much!! This is EXACTLY what we were looking for. Your help saved us!! :):):):)
Cheers,
Mike
Hi,
Thank you for this article.
Is it possible for me to download the complete source code?
I am trying to implement, but couldn’t be successful.
Thank you,
Maria
I’ve also found this doesn’t work in IE6 or Opera. In fairness, I am using a standalone version of IE6, installed alongside IE7, so I can’t be sure if the problem is with the browser and not the idea of sending a file through an iframe.
However with Opera, which is installed correctly, I’m getting the same behavior — file just does not download through the iframe like it does in IE7, FF, and Safari. I read the comments, and I am using the correct contenttype for the file being downloaded:
string path = MapPath(“~/EmptyDownload.zip”);
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + fileInfo.Name);
Response.AddHeader(“Content-Length”, fileInfo.Length.ToString());
Response.ContentType = “application/zip”;
Response.Write(fileInfo.FullName);
Response.End();
}
For IE6 and Opera, it seems like you need to open a popup window to force the download.
Dave,
Thanks for the workaround.
I have a page with multiple update panels and file download needs to happen in one of the user control in update panel.
I have come with slightly different way where you dont have to worry about the id of the source element and
InitializeRequest() event.
I basically created script block on server side and registered with ScriptManager.
We dont need to use IFRAME. Just use anchor ‘‘ and provide the link in the href along with your parameters (if any). The browsers are intelligent enough to open up download dialog by looking at the header content type.
http://code.msdn.microsoft.com/AjaxFileDownload
A ‘Big Thanks’ to you, Dave. You helped me out of a tight spot!
I used the recommendation above from richie – adding the linkbutton into the gridview. I was having some trouble with the command argument not coming through correctly so I added this to the RowDataBound Sub…
Dim lb1 As LinkButton = DirectCast(e.Row.FindControl(“lbFile”), LinkButton)
lb1.CommandArgument = e.Row.RowIndex
Worked great.
Thanks for the great blog Dave!
Very nice – I never would have thought about this, but it worked perfectly. I have the same issue, where I was making an AJAX call prior to popping up a new window with the Excel document – IE default settings stopped it. I applied this technique, and everything magically works, in all browsers.
Nice work.
Nice article.
One small question. if i need to pass large data. lets a csv data. it is not gud way to pass through query string.
Is there any other way to pass data to generic handler(im using)
Please help me out
Thanks Ahead!!!
Regards
Great Solution !
Thx !!!
Thanks a ton, Dave! This solution still holds worlds of value.
I have tried this and working fine. But I had problem… I am getting JavaScript error after downloading the file. it is just undefined error. Even though I got the error I am able to download the file. Please help me resolve the error.
This code doesn’t run any JavaScript after the download, only at the beginning to inject the iframe. Can you be more specific about what error you’re seeing?
Dave, i want to show a animated gif in the begin and the end of the process while the file is being created, is there a way to do this ?
I haven’t tried it myself, but you might be able to do that by attaching on onload handler to the iframe. Show the progress indicator in that initializeRequest handler and then hide it in the iframe’s onload.
Thanks a ton Dave!! Great Solution!!!!
Hi all!
Please help me to resolve the problem. When I click on the button for the first time, everything is OK and the PDF is created, a download dialog appears. Inside the code: first runs on the button click event (which creates a PDF), then runs JavaScrip function and opens a download page with parameters of just created file. But when I click a second time the click event doesn’t run, just JavaScrip function. Pleas tell me how I can run always click event before.
Regards.
That worked great, just enclose controls names with server tags
Thank you.
Worked great. I kind of generalized this to download on a button click and linked it to a another aspx file instead. My code sample below if it helps anyone else
this script below goes where you have the Button to download the file where imgDownload defintion is lke this. don’t need to do anything on imgDownload_Click, but still need it there.
And write a Download.aspx which is a plain aspx file with just the below code in page_load. In my case, I’m assuming the Session variable for the File is set and I’m just pulling the file name from a DB and identifying the Extension type and pulling the binary stream of that file from the DB as well.
Hope this helps someone else in the future.
hi, thanks for the great code dave… really great!
i used your code in my page where i have ajax tabcontainer control which have multiple tabpanels and each tabpanel contains asp chart control .. when i use your code and click generate report file generates perfectly but when i go to my inactive tabpanels my asp charts gone blank ( not showing chart image) any ideas?
stuck in it since monday !!
Sim sai