且构网

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

从服务器ASP.net文件下载

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

您可以使用HTTP处理程序(ashx的)下载文件,就像这样:

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

DownloadFile.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;
        }
    }
}

然后就可以调用从按钮单击事件处理的HTTP处理程序,如:

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"/>

code-背后:

Code-Behind:

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

然后在实际的处理器code,你可以使用请求对象的的HttpContext 抢查询字符串变量值,就像这样:

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...