簡體   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