在我的应用程序中,用户可以在单击链接后下载文件.文档是在代码中生成的PDF/RTF.我用:
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();
Run Code Online (Sandbox Code Playgroud)
它工作正常,但这通常是一个好方法吗?为什么要冲洗两次?我找到了许多不同的例子,这个很好但有时我得到The remote host closed the connection. The error code is 0x80070057错误.我找到了应该使用的解决方案
if (Response.IsClientConnected)
{
Response.Flush();
Response.End();
}
Run Code Online (Sandbox Code Playgroud)
整个代码应该如何?
我不明白你为什么要打Flush()两次电话。打电话后,一个就够了BinaryWrite()。
第一次调用将Flush()标头发送到浏览器,包括Content-Length,这在调用时仍然未知 - 或者根本就是错误的。
End()另外,除非绝对必要,否则我会避免打电话。
| 归档时间: |
|
| 查看次数: |
17035 次 |
| 最近记录: |