1:编写一个实现IHttpHandler的类。
public
class
DownloadFileProcesser : IHttpHandler
...
{ private DownLoadData logdata = new DownLoadData(); public DownloadFileProcesser() ... { } public void ProcessRequest(HttpContext context) ... { string fileName = context.Request.Url.OriginalString; // 获取请求的url string ORIGINALURL = fileName; // 完整的请求路径 int index = fileName.LastIndexOf( " / " ); // 取最后一个/的未知 fileName = fileName.Substring(index + 1 ); string filepath = fileName; int iBegin = fileName.LastIndexOf( " _ " ); // 取"_"之前和"."后面的,组成aaa.dd int iEnd = fileName.LastIndexOf( " . " ); string localPath = System.Configuration.ConfigurationManager.AppSettings[ " downLoadPath " ]; // 下载文件的存放路径 if (iBegin >= 0 ) ... { filepath = fileName.Substring( 0 , iBegin) + fileName.Substring(iEnd); filepath = context.Server.MapPath(localPath + filepath); } else ... { // filepath = Path.Combine(localPath, fileName); filepath = context.Server.MapPath(localPath + fileName); } // downLoadHandle aa = new downLoadHandle(outputBinary); if (File.Exists(filepath)) // 文件是否存在。不存在的话按照真实文件名下载 ... { outputBinary(fileName, filepath, context); sendState = 1 ; } else ... { context.Response.Status = " 404 Not Found " ; sendState = 0 ; } logdata.SENDSTATE = sendState; int indexLfn = filepath.LastIndexOf( " / " ); string localFileName = filepath.Substring(index1 + 1 ); logdata.LOCALFILENAME = localFileName; logdata.ORIGINALURL = ORIGINALURL; WriteDownLoadLog(); } // 文件按照二进制流循环输出。其实没必要这么写。 public void outputBinary( string fileName, string filepath, HttpContext context) ... { context.Response.ContentType = " application/octet-stream " ; context.Response.AppendHeader( " Content-Disposition " , " attachment; filename= " + fileName); using (System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) ... { byte [] aLogData = new byte [ 1024 ]; int len; // 设定每次读取1024个字节。避免多人下载时过慢。 while ((len = fs.Read(aLogData, 0 , aLogData.Length)) > 0 ) ... { context.Response.BinaryWrite(_FixBuffer(aLogData, len)); } } } /**/ /// <summary> /// 取指定长度的文件 /// </summary> /// <param name="aLogData"></param> /// <param name="len"></param> /// <returns></returns> private byte [] _FixBuffer( byte [] aLogData, int len) ... { if (aLogData.Length == len) return aLogData; byte [] buffer = new byte [len]; Array.Copy(aLogData, buffer, len); return buffer; } public bool IsReusable ... { get ... { return true ; } } }
2:配置webconfitg
<httpHandlers>
<!--当请求的后缀为.cab的时候,调用DownloadFileProcesser这个继承IHttpHandler接口的类-!> <add verb="GET,POST" path="*.cab" type="DownloadFileProcesser"/> </httpHandlers>
3:运行IIS服务管理器,右键点击默认Web站点,选择属性,移动到Home目录选项页,并点击配置按钮。应用程序配置对话框弹出来了。点击添加按钮并在可执行字段输入aspnet_isapi.dll文件路径,在扩展字段输入.kim ps:如果你的操作系统是XP SP2的话,在输入aspnet_isapi.dll路径时需要手工输入,不能用复制粘贴的形式,否则保存按钮变灰。浏览时去掉check file exit选项。