views:

1028

answers:

3

Hi,

I want to provide dynamic download of files. These files can be generated on-the-fly on serverside so they are represented as byte[] and do not exist on disk. I want the user to fill in an ASP.NET form, hit the download button and return the file he/she wanted.

Here is how my code behind the ASP.NET form looks like:

public partial class DownloadService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void submitButtonClick(object sender, EventArgs e)
{
    if (EverythingIsOK())
    {
        byte[] binary = GenerateZipFile(); 
        Response.Clear();
        Response.ContentType = "application/zip";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.BinaryWrite(binary);
        Response.End();
    }
}
...
}

I expected this piece of code just work. I clear the Respone, put in my generated zip file and bingo. However, this is not the case. I get the following message in the browser:

The XML page cannot be displayed Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later. An invalid character was found in text content. Error processing resource 'http://localhost:15900/mywebsite/DownloadS...

What am I doing wrong?

A: 

Look here for informationa about application/zip . It might be that the ContentEncoding is wrong. And here's a guide on sending other types. Also here is a guide on how to do it for pdfs.

Filip Ekberg
+2  A: 

Here's a minor modification you need to make:

Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.BinaryWrite(binary);
Response.End();
Darin Dimitrov
There is actually a content type called appliaction/zip
Filip Ekberg
Yes, I know that there is application/zip content type. What I am saying is that you have to use application/x-zip-compressed instead if you want your application to work correctly in IE.
Darin Dimitrov
In fact in some cases IE tries to be smart and uses the FindMimeFromData function to guess the mime type ignoring the one specified by the Content-Type header.
Darin Dimitrov
+1  A: 

This is my (working) implementation:

Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0} {1} Report for Week {2}.pdf\"", ddlClient.SelectedItem.Text, ddlCollectionsDirects.SelectedItem.Text, ddlWeek.SelectedValue));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

mimeType is like your application/zip (except PDF). The main differences are the extra header information passed, and the Flush call on the Response object.

ck