栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从服务器下载ASP.NET文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从服务器下载ASP.NET文件

您可以使用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

注意 -通常将文件名作为查询字符串参数传递,以向用户建议文件的实际位置,在这种情况下,他们可以使用“另存为”来覆盖该名称值。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415358.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号