using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace NetWorkHardNew.GlobalAshx { /// /// DownFile 的摘要说明 /// public class DownFile : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpFileCollection files = context.Request.Files; string FilePath = context.Server.UrlDecode(context.Request.QueryString["FilePath"]); string FileName = context.Server.UrlDecode(context.Request.QueryString["FileName"]); if (FilePath == "") return; FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath; string ext = Path.GetExtension(FilePath); if (ext == ".aspx" || ext == ".config" || ext == ".dll" || FilePath == "/Setup.ini" || FilePath == "Setup.ini") { context.Response.End(); return; } context.Response.Clear(); context.Response.ClearHeaders(); context.Response.Buffer = true; context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.GetEncoding("utf-8"))); context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 context.Response.ContentType = "application/octet-stream"; if (Path.GetExtension(FileName) == ".doc") context.Response.ContentType = "application/ms-word"; if (Path.GetExtension(FileName) == ".xls") context.Response.ContentType = "application/ms-excel"; if (Path.GetExtension(FileName) == ".pdf") context.Response.ContentType = "application/pdf"; if (System.IO.File.Exists(FilePath) == true) { FileInfo fi = new FileInfo(FilePath); FileStream fs = null; byte[] buffer = new Byte[10000]; int length; long dataToRead; try { fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read); context.Response.AppendHeader("Content-Length", fs.Length.ToString()); dataToRead = fs.Length; while (dataToRead > 0) { if (context.Response.IsClientConnected) { length = fs.Read(buffer, 0, 10000); context.Response.OutputStream.Write(buffer, 0, length); context.Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { dataToRead = -1; } } } catch { } finally { if (fs != null) { fs.Close(); } context.Response.End(); } } } public bool IsReusable { get { return false; } } } }