issue with Response.OutputStream.Write adding html

2019-08-12 08:05发布

问题:

I read in a text file and try to push it to the browser to prompt a user to download but I'm getting my data plus HTML code inside the file. What am I screwing up? Thanks.

byte[] eftTextFile = ...calls a method that returns a byte array (does a File.ReadAllBytes on a txt file)

Then I try:

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", fileName));
Response.AddHeader("Content-Length", eftTextFile.Length.ToString());
Response.OutputStream.Write(eftTextFile, 0, eftTextFile.Length);
Response.Flush();

This is my aspx.cs file and is the result of a button click. which is a simple:

<asp:Button ID="btnCreate" Text="Create" runat="server" OnClick="btnCreate_Click">

回答1:

Just write at the end

Response.End();


回答2:

I tried using "HttpContext.Current.ApplicationInstance.CompleteRequest(); but that did not work. The only thing I could get to work was using Response.End(). Not sure why one works and the other doesn't.



回答3:

This might be of your interest:

Large binary over asmx web service

It uses a web method, which is pretty much as efficient as it can get, and there's very little coding involved.



回答4:

You need to make a call to CompleteRequest() at the end.

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"",    fileName));
Response.AddHeader("Content-Length", eftTextFile.Length.ToString());
Response.OutputStream.Write(eftTextFile, 0, eftTextFile.Length);
Response.Flush();
//now signal the httpapplication to stop processing the request.
HttpContext.Current.ApplicationInstance.CompleteRequest();

Calling CompleteRequest is superior to calling Response.End() in that it shuts the response down correctly and gets around some of the issues in internet explorer brought up in this question:

IE 10 - File download issues



回答5:

Your problem may be very simple; you have this...

attachment;filename

...where you should (according to spec) have this:

attachment; filename

Note the space character.