HttpHandler实现简单文件下载
ASP.Net处理Http Request的相关流程
ASP.Net处理Http Request时,使用Pipeline(管道)方式,由各个HttpModule对请求进行处理,然后到达 HttpHandler,HttpHandler处理完之后,仍经过Pipeline中各个HttpModule的处理,最后将HTML发送到客户端浏览器中。
用自定义的HttpHandler来完成文件下载功能
自定义HttpHandler代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
namespace HttpHandlerSample
{
public class Downloader : IHttpHandler, IRequiresSessionState
{
private HttpRequest Request
{
get { return HttpContext.Current.Request; }
}
private HttpResponse Response
{
get { return HttpContext.Current.Response; }
}
private string FileName
{
get
{
return Request["FileName"].ToString();
}
}
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string filePath = HttpContext.Current.Server.MapPath("File/" + FileName);
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] fileBytes = new byte[(int)fs.Length];
fs.Read(fileBytes, 0, fileBytes.Length);
fs.Close();
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
Response.End();
}
#endregion
}
}
Web.Config 配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<httpHandlers>
<add verb="*" path="Downloader.dl" type="HttpHandlerSample.Downloader"/>
</httpHandlers>
使用范例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<div>
<asp:HyperLink ID="HyperLink1" Text="Word.doc" NavigateUrl="~/Downloader.dl?FileName=Word.doc" runat="server"></asp:HyperLink>
<br />
<asp:HyperLink ID="HyperLink2" Text="Text.txt" NavigateUrl="~/Downloader.dl?FileName=Text.txt" runat="server"></asp:HyperLink>
<br />
<asp:HyperLink ID="HyperLink3" Text="Excel.xls" NavigateUrl="~/Downloader.dl?FileName=Excel.xls" runat="server"></asp:HyperLink>
</div>
参考资料:
http://www.rainsts.net/article.asp?id=286