簡體   English   中英

如何使用ASP.NET下載文件

[英]How to download a file using ASP.NET

在下面的代碼中,當我單擊鏈接按鈕時,我想從本地下載文件,它應該從特定路徑下載文件。 就我而言

“ C:/Search/SVGS/Documents/img.txt”是物理路徑,但是應該使用虛擬路徑。

protected void lnkbtndoc_Click(object sender, EventArgs e)
{
    LinkButton lnkbtndoc = new LinkButton();
    var SearchDoc = Session["Filepath"];
    string file = SearchDoc.ToString();
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + file + "\"");
    Response.TransmitFile(Server.MapPath(file));
    Response.End();
}

使用以下代碼下載文件,然后單擊鏈接按鈕

<asp:LinkButton ID="btnDownload" runat="server" Text="Download"
            OnClick="btnDownload_OnClick" />
protected void btnDownload_OnClick(object sender, EventArgs e)
    {
        string filename = "~/Downloads/msizap.exe";
        if (filename != "")
        {
            string path = Server.MapPath(filename);
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }

在您的代碼中,只需更改以下行:

Response.TransmitFile(Server.MapPath(file));

Response.TransmitFile(file);

這是因為您發送的是物理路徑,而不是Server.MapPath期望的虛擬路徑。 還請閱讀本文 ,它將幫助您了解如何處理Server.MapPath方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM