issue with Response.OutputStream.Write adding html code in the resulting file

青春壹個敷衍的年華 提交于 2019-12-11 05:34:09

问题


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.



来源:https://stackoverflow.com/questions/21391484/issue-with-response-outputstream-write-adding-html-code-in-the-resulting-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!