Friday, March 6, 2009

Streaming a zip file from an ASP.NET web site

I was recently having a really tough time trying to debug the streaming of a zip file from an ASP.NET web app to a browser. The code was fairly simple and is repeated all over the web which gave me confidence in how robust it is:

FileInfo toDownload = new FileInfo(fullFileName);
if (toDownload.Exists)
{
   Response.Clear();
   Response.ContentType = "application/zip";
   Response.AppendHeader("Content-Disposition", "attachment;filename=" +
          toDownload.Name);
   Response.AppendHeader("Content-Length", toDownload.Length.ToString());
   Response.TransmitFile(fullFileName);
   Response.End();
}

The client side error that I was getting was:

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near 'PK...'.

The good thing about seeing the "PK" in the error is that it told me that the server was indeed sending the zip file. The first two characters in a zip file are PK which is one way to identify a zip file by opening it and reading the first two characters.

The control on the web page that kicked off the download action shown above was inside an UpdatePanel and it was this that was causing the problem. Eilon Lipton wrote the error message above and he explains it in this blog post

The solution it turns out is to put a PostBackTrigger in the UpdatePanel:

<Triggers>
   <asp:PostBackTrigger ControlID="ibDownload" />
</Triggers>

This will force the click to do a regular postback instead of an asyncronous postback and solved the problem.

5 comments:

  1. Thanks alot.... I would have never picked this one up.

    ReplyDelete
  2. Thank you so much, it saved my life. :)

    ReplyDelete
  3. Thank you so much, it saved my life..yea!!! :))

    ReplyDelete