从服务器下载ASP.NET文件

Jam*_*son 41 c# asp.net

用户单击按钮后,我想要下载文件.我已经尝试了以下似乎可以工作,但不是没有抛出一个不可接受的异常(ThreadAbort).

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
    response.TransmitFile(Server.MapPath("FileDownload.csv"));
    response.Flush();
    response.End();  
Run Code Online (Sandbox Code Playgroud)

Kar*_*son 77

您可以使用HTTP处理程序(.ashx)下载文件,如下所示:

DownloadFile.ashx:

public class DownloadFile : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {   
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", 
                           "attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath("FileDownload.csv"));
        response.Flush();    
        response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以从按钮单击事件处理程序中调用HTTP处理程序,如下所示:

标记:

<asp:Button ID="btnDownload" runat="server" Text="Download File" 
            OnClick="btnDownload_Click"/>
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

protected void btnDownload_Click(object sender, EventArgs e)
{
    Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Run Code Online (Sandbox Code Playgroud)

将参数传递给HTTP处理程序:

您可以简单地将查询字符串变量附加到Response.Redirect(),如下所示:

Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Run Code Online (Sandbox Code Playgroud)

然后在实际的处理程序代码中,您可以使用该Request对象HttpContext来获取查询字符串变量值,如下所示:

System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here
Run Code Online (Sandbox Code Playgroud)

注意 - 通常将文件名作为查询字符串参数传递给用户建议文件实际是什么,在这种情况下,他们可以使用另存为覆盖该名称值...

  • 我在事件处理程序中的“Server.MapPath()”中收到错误:“Server” (4认同)

Rob*_*eph 9

尝试使用这组代码从服务器下载CSV文件.

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Run Code Online (Sandbox Code Playgroud)