如何在Htt的presponse发送文件? [英] How to send file in HttpResponse?
问题描述
在我的应用程序的用户点击一个链接后,可以下载一个文件。文档在code生成的PDF / RTF。我使用的:
In my application user can download a file after clicking a link. Document is PDF/RTF generated in code. I use:
byte[] downloadBytes = some pdf document bytes...
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=filename.pdf; size=" + downloadBytes.Length.ToString());
response.Flush();
response.BinaryWrite(downloadBytes);
response.Flush();
response.End();
它的工作原理确定,但就是这通常一个好方法吗?为什么冲洗被称为两次?我发现很多不同的例子,这一次工作得很好,但有时我得到了远程主机关闭了连接。错误code是80070057
错误。我找到的解决方案,我应该使用
It works OK but is this generally a good way ? Why flush is called two times? I found many different examples and this one works fine but sometimes I got The remote host closed the connection. The error code is 0x80070057
error. I found solution that I should use
if (Response.IsClientConnected)
{
Response.Flush();
Response.End();
}
如何在整个code应该是什么样子?
How the entire code should look like?
推荐答案
下面是我用code。它不叫齐平的。我不知道这是否是正确的做法,但它为我工作。
Here is the code that I use. It does not call flush at all. I am not sure if it is the right way, but it works for me.
public static void ResponseOpenFileBytes(byte[] File, string ContentType, string SaveAsFileName, HttpResponse response)
{
if (string.IsNullOrEmpty(ContentType))
{
ContentType = "application/octet-stream";
}
response.Clear();
response.AddHeader("content-disposition", "attachment;filename=" + SaveAsFileName);
response.ContentType = ContentType;
response.BinaryWrite(File);
response.End();
}
这篇关于如何在Htt的presponse发送文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!