【问题标题】:ASP C# Send File to ClientASP C# 向客户端发送文件
【发布时间】:2013-11-04 23:00:39
【问题描述】:

尝试将文件发送到浏览器进行下载,但在摆弄了一个多小时后似乎无法正常工作。

我正在使用以下代码

    string filePath = Server.MapPath("/exports/test.txt");
    string downloadedFileName = "test.txt";

    Response.ContentType = "text/plain";
    Response.AppendHeader("content-disposition", "attachment; filename=" + downloadedFileName);
    Response.TransmitFile(filePath);
    Response.End();

它下载到浏览器,但文件中填充了来自页面的 HTML,而不是文件的内容。如果我写出 server.MapPath 的目录,则该文件位于该目录中。

我最终将使用它来将 accdb 或 mdb 数据库发送到浏览器,我只是使用 txt,因为很容易在网上找到概念证明示例。如果有的话,我需要在 ContentType 之外进行什么更改。 ContentType 也应该用于数据库吗?

提前感谢您的帮助!

【问题讨论】:

标签: c# asp.net


【解决方案1】:

这可能是因为响应流中已经有一些输出排队等待传输。在传输文件之前,您必须先清除它。如果您使用的是 ASP.NET Web 表单,这将破坏您的页面,因为回发行为将不再起作用。

查看related SO question 并回答。

【讨论】:

    【解决方案2】:

    这就是我通常的工作方式:

    Response.Clear();
    
    if (Request.Browser != null && Request.Browser.Browser == "IE")
        sFileName = HttpUtility.UrlPathEncode(sFileName);
    
    // Response.Cache.SetCacheability(HttpCacheability.Public); // that's upon you
    
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + "\"");
                                                                // ^                   ^
    // Response.AddHeader("Content-Length", new FileInfo(sFilePath).Length.ToString()); // upon you 
    Response.WriteFile(sFilePath);
    
    Response.Flush();
    Response.End();
    

    【讨论】:

      【解决方案3】:

      尝试使用 .ashx 通用处理程序绕过大部分 ASP.NET 堆栈将文件发送到浏览器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-27
        • 2014-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多