Preventing extra HTML Content in File Downloads

We've had several discussions on site about difficulties with getting extra HTML content appended to the end of a file when using a response-header generated file download dialog for the browser.

We've had several discussions on site about difficulties with getting extra HTML content appended to the end of a file when using a response-header generated file download dialog for the browser.

Since I recently encountered this problem myself and had to go looking around because I couldn't remember exactly how to handle it, I figured it would be useful to post the code here. This one worked fine for me, "YMMV".

"strFileName" is the name of the file you would like the browser to use in the download dialog, and "StrFileData" is the string holding the content. If this is binary content (graphic, Excel worksheet, etc. ) you would use the Response.BinaryWrite()
method.



Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
// add the header that specifies the file size, so that the browser
// can show the download progress
Response.AddHeader("Content-Length", strFileData.Length.ToString());
// specify that the response is a stream that cannot be read by the
// client and must be downloaded
Response.ContentType = "application/octet-stream";
// send the file stream to the client
Response.Write(strFileData);
Response.End();



Submission Date:  9/23/2005 3:23:00 PM
Submitted By:  Peter Bromberg
My Home Page:  http://www.eggheadcafe.com

By Peter Bromberg   Popularity  (408 Views)