且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从服务器下载 ASP.NET 文件

更新时间:2023-02-16 22:32:21

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

You can use an HTTP Handler (.ashx) to download a file, like this:

下载文件.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;
        }
    }
}

然后你可以从按钮点击事件处理程序中调用HTTP Handler,像这样:

Then you can call the HTTP Handler from the button click event handler, like this:

标记:

<asp:Button ID="btnDownload" runat="server" Text="Download File" 
            OnClick="btnDownload_Click"/>

代码隐藏:

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

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

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

You can simply append a query string variable to the Response.Redirect(), like this:

Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");

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

Then in the actual handler code you can use the Request object in the HttpContext to grab the query string variable value, like this:

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

// Use the yourVariableValue here

注意 - 通常将文件名作为查询字符串参数传递给用户,以向用户建议文件的实际内容,在这种情况下,他们可以使用另存为...

Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...