【问题标题】:Serve static file in ASP.NET在 ASP.NET 中提供静态文件
【发布时间】:2015-10-23 20:47:35
【问题描述】:

我只是想在我的解决方案的文件夹中放置一个 pdf 文件,然后让用户在我的网站上下载它。很简单!

我有一个 .aspx 主页面,其中包含指向另一个 .aspx 页面的静态链接,我仅使用该链接来下载文件。如果我直接从 Visual Studio 中运行下载页面,则该代码有效,但是如果我运行我的主页并单击我指向此页面的那个,则它不起作用。这是下载页面的代码:

FileInfo file = new FileInfo(Server.MapPath("~/Workflow/Workflow v3.pdf"));            
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";;
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.BinaryWrite((byte[])File.ReadAllBytes(Server.MapPath("~/Workflow/Workflow v3.pdf")));
Response.Flush();
Response.End();

仅供参考。这是我在工具的不同区域使用的另一个下载页面。这个页面实际上是带一个参数,并点击数据库来抓取存储在数据库中的文件。此代码确实有效,但我不想为我的“工作流程”下载页面这样做。

        ...
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = AgreementDocumentTable.Rows[0]["ContentType"].ToString();
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + AgreementDocumentTable.Rows[0]["Title"].ToString());
        Response.BinaryWrite((byte[])AgreementDocumentTable.Rows[0]["AgreementDocument"]);
        Response.Flush();
        Response.End();

【问题讨论】:

  • 你需要更清楚“不起作用”。断点会被击中吗?有例外吗?等
  • 它在 Response.End(); System.Web.dll 中出现“System.Web.HttpException”类型的异常,但未在用户代码中处理附加信息:远程主机关闭了连接。错误代码为 0x80070057。
  • 我了解 Response.End() 会按设计抛出异常。但仍然没有进行下载。

标签: c# asp.net file download binaryfiles


【解决方案1】:

【讨论】:

  • 抱歉,这没有帮助。我仔细阅读了你的两个链接,并尝试了一些不同的东西,这些信息在这些帖子中,但都不起作用。我得到相同的“远程主机关闭了连接”。错误。
【解决方案2】:

通过调用 javascript 函数并使用 ScriptManager.RegisterClientScriptBlock 来实现此功能

这项工作(不知道 100% 的原因,希望得到解释)所以我将继续使用它......

标记:

<a runat="server" id="WorkflowDownloadLink" onserverclick="DownloadWorkflowLink_Click" href="">

事件代码:

protected void DownloadWorkflowLink_Click(Object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Download", "GotoDownloadPage('./Workflow.aspx');", true);
    }

Workflow.aspx 上的代码:

protected void Page_Load(object sender, EventArgs e)
    {

        FileInfo file = new FileInfo(Server.MapPath("~/Workflow/Workflow v3.pdf"));

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
        Response.BinaryWrite((byte[])File.ReadAllBytes(Server.MapPath("~/Workflow/Workflow v3.pdf")));
        Response.Flush();



    }

【讨论】: