您可以使用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;
}
}
}
然后可以从按钮单击事件处理程序调用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");
}
Passing a parameter to the HTTP Handler:
您只需将查询字符串变量附加到Response.Redirect()
,如下所示:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
然后在实际的处理程序代码中,可以使用HttpContext
中的Request
对象来获取查询字符串变量值,如下所示:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note-通常将文件名作为查询字符串参数传递给用户,以建议用户该文件实际是什么,在这种情况下,他们可以用另存为.覆盖该Name值.