【问题标题】:Exception : "The remote host closed the connection. The error code is 0x80070057"异常:“远程主机关闭连接。错误代码为 0x80070057”
【发布时间】:2015-03-29 16:44:45
【问题描述】:

我遇到了这个异常。 我遵循了中给出的建议 What does this error mean? The remote host closed the connection. The error code is 0x80070057

仍然,我得到了同样的错误。

我正在使用Response.WriteFile() 将文件从服务器传输到客户端浏览器。

在视图中:

  $("#btnExport").on("click", function (e) {
      window.location = '@Url.Action("ExportToExcel", "Report")';
       e.preventDefault();
  });

在控制器中:

[HttpGet]
public RedirectResult ExportToExcel()
{
    Download(ExportFilePath);    
    return new RedirectResult(ExportFilePath); 
}

public void Download(ExportFilePath)
{
    HttpContext context = System.Web.HttpContext.Current;
    FileInfo file = new FileInfo(ExportFilePath);
    context.Response.Clear();
    context.Response.ClearHeaders();
    context.Response.ClearContent();
    context.Response.AppendHeader("Content-Disposition", "attachment; filename =" + ExportFileName);
    context.Response.AppendHeader("Content-Length", file.Length.ToString());
    context.Response.ContentType = "application/excel";
    context.Response.WriteFile(file.FullName);
    context.Response.Flush();
    context.Response.Close();
    context.Response.End();
}

【问题讨论】:

  • 你的RedirectResult(ExportFilePath)有点奇怪。它应该是url,页面应该被重定向,而不是文件路径
  • @rock_walker :我可以在其中放置 Download() 方法的建议的操作实现是什么。
  • @BhaweshPaliwal 该错误仅表示用户在所有内容从服务器发送到客户端之前关闭了浏览器,例如客户端请求文件,服务器开始传输文件,但在服务器完成发送文件之前,用户关闭浏览器......基本上你无能为力。
  • @BhaweshPaliwal。我使用简单的 *.txt 文件在我的本地主机上应用了您的代码示例。没有错误,我成功下载了文件。
  • @BhaweshPaliwal。如果您使用 VS2013 和/或 IIS8,则可能会更深入地寻找 SignalR 问题。尝试在 VS 中禁用 BrowserLink。抱歉,我只能猜到这个建议,因为我的主机上安装了 VS2012 和 IISExpress。

标签: javascript c# asp.net-mvc


【解决方案1】:

我遇到了同样的问题,你应该尝试删除下面的代码行

context.Response.WriteFile(file.FullName);
context.Response.Flush();
context.Response.Close();
context.Response.End();

添加波纹管

context.Response.TransmitFile(strFileName);

解决方案 2:

FileStream myFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long FileSize = myFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
myFileStream.Read(Buffer, 0, (int)FileSize);
myFileStream.Close();
myFileStream.Dispose();

Response.ContentType = "image/jpeg";
Response.AddHeader("Content-Type", "image/jpeg");
Response.AddHeader("Content-Disposition", "attachment;filename=FILENAME.jpg");

Response.BinaryWrite(Buffer);
Response.End();

如果上述解决方案不适合您,请告诉我。

【讨论】:

  • 谢谢!你的两个解决方案都对我很有效。
  • 然后通过接受这个作为回答并投票 +1 来感谢它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多