简体   繁体   English

如何使用ASP.NET下载文件

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

In the below code i want to download a file from local when i click link button it should download a file from specific path. 在下面的代码中,当我单击链接按钮时,我想从本地下载文件,它应该从特定路径下载文件。 In my case it throws 就我而言

'C:/Search/SVGS/Documents/img.txt' is a physical path, but a virtual path was expected. “ 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();
}

Use the below code to download the file on link button click 使用以下代码下载文件,然后单击链接按钮

<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.");
            }
        }
    }

In your code just change this line : 在您的代码中,只需更改以下行:

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

to

Response.TransmitFile(file);

This because of you are sending the physical path not the virtual path as Server.MapPath expects. 这是因为您发送的是物理路径,而不是Server.MapPath期望的虚拟路径。 Also read this article it will help you to understand how to deal with Server.MapPath method 还请阅读本文 ,它将帮助您了解如何处理Server.MapPath方法

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

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