Reputation: 1247
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?
Upvotes: 1
Views: 3009
Reputation: 46475
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.
Upvotes: 2
Reputation: 1039508
Here's a minor modification you need to make:
Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.BinaryWrite(binary);
Response.End();
Upvotes: 2
Reputation: 36327
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.
Upvotes: 0