您可以使用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; } }}然后,您可以从按钮click事件处理程序中调用HTTP处理程序,如下所示:
标记:
<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(),如下所示:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");然后,在实际的处理程序代码中,您可以使用中的
Request对象
HttpContext来获取查询字符串变量值,如下所示:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;string yourVariablevalue = request.QueryString["yourVariable"];// Use the yourVariablevalue here
注意 -通常将文件名作为查询字符串参数传递,以向用户建议文件的实际位置,在这种情况下,他们可以使用“另存为”来覆盖该名称值。



