在ASP.NET中提供静态文件

时间:2015-10-23 20:47:36

标签: c# asp.net file download binaryfiles

我只是想将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();

2 个答案:

答案 0 :(得分:0)

我能够找到这个答案,解释你不应该使用Response.End(),而是建议使用CompleteRequest()方法。

HttpContext throws HttpException

http://blogs.msdn.com/b/aspnetue/archive/2010/05/25/response-end-response-close-and-how-customer-feedback-helps-us-improve-msdn-documentation.aspx

答案 1 :(得分:0)

通过调用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();



    }