繁体   English   中英

在ASP.NET中提供静态文件

[英]Serve static file in ASP.NET

我只是想将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(),而是建议您使用CompleteRequest()方法。

HttpContext抛出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

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



    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM