2010/12/18

Doing some work after Response.End() (11/14/2013 updated)

I need to do something that after users download a file from my website. Most file downloading approach is using something like this:
//data preparation at here...

Page.Response.ClearContent();
Page.Response.ClearHeaders();
Page.Response.Clear();
Page.Response.Buffer = true;
Page.Response.ExpiresAbsolute = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0));
Page.Response.Expires = 0;
Response.AddHeader("content-disposition", "attachment;filename=" + YourFileNameHere + ".xls";
//here I use excel file type
Response.ContentType = "application/vnd.ms-excel";
//FileContent is a string variable which stores your file content
Page.Response.AddHeader("content-length", FileContent.Length.ToString());
Response.Write(FileContent);
Response.End();

As many of you already know, codes after the Response.End() will not work. Here is an interested thread that you can refer to.

I tested all those approaches mentioned in that thread. Some people said some methods work for them, but none of those suggestions work for me. I am using .Net 4. After hour and hour testing, I finally found a way (from a senior developer) that works for me: use something like ModalPopup. I didn't use this Microsoft Ajax controltoolkit. Instead, I use div + iframe (hand build javascript) to achieve the same thing. Concept is the same:
1. Use this iframe (or modalpopup) to handle the file download stuff.
2. After completing the download, close that iframe (or modalpopup) and then you can keep doing whatever you want after the file download.


Reference:
Ending a Response without Response.End() Exceptions?
ModalPopup Demonstration

11/14/2013:
I finally remember to find out the codes that some people were asking for. I created a simple proof-of-concept (poc) project and copy the codes to there. Some functions in codes are not provided. Remember, this is just a poc project. The key (main) point is the concept! :)

You can download this simple poc project at here.

6 comments:

  1. Can i have the attachment of code that you have worked on this

    ReplyDelete
  2. Sure. Everything on this blog is public.

    ReplyDelete
  3. Hi Kenny, Can you please send the code to Voodaravikumar@gmail.com

    ReplyDelete
  4. It takes time to find out the old codes. I will find out and post it here (when I have free time :)).

    ReplyDelete
  5. can u share the code please

    ReplyDelete
  6. plz share code or send me hosseinhagh66@gmail.com
    thanks

    ReplyDelete