.net一般处理程序(httphandler)实现文件下载功能
Handler文件代码如下:
public class MDMExporterWeb : IHttpHandler { public void ProcessRequest(HttpContext context) { string url = context.Request.Form["fileName"]; //判断服务端是否生成Excel文件 if (File.Exists(context.Server.MapPath(url))) { //获取文件路径和文件名 string filePath = context.Server.MapPath(url); string fileName = Path.GetFileName(filePath); //将文件转换为字节流 //byte[] file = ImpExpWebPublic.ConvertToBinary(filePath); FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); using (MemoryStream stream = new MemoryStream(bytes)) { //文件导出到客户端(Web) ResponseFile(context.Request, context.Response, fileName, stream, 10240); } } else { context.Response.Write("<script> alert('错误信息:未导出Excel文件');window.close();</script>"); } } public bool IsReusable { get { return false; } } /// <summary> /// 文件下载 /// </summary> /// <param name="_Request">Request对象</param> /// <param name="_Response">Response对象</param> /// <param name="_fileName">文件名</param> /// <param name="stream">发送的流</param> /// <param name="block">每次读取的字节数</param> /// <returns></returns> public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, Stream stream, int block) { try { _Response.Clear(); using (var br = new BinaryReader(stream)) { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long fileLength = stream.Length; long startBytes = 0; int pack = block; //每次读取的字节数 if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); if (startBytes != 0) { _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + Uri.EscapeUriString(_fileName)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((fileLength - startBytes) / (double)pack) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); } else { i = maxCount; } } br.Close(); stream.Close(); } } catch (Exception e) { _Response.Write(e.Message + e.StackTrace); _Response.Flush(); } return true; } }
javascript代码如下:
var fileName = '/cwbase/test1.xls';//相对路径 var postUrlE = '/cwbase/MDMWeb/MDMExporterWeb.ashx'; var form = $('<form action="' + postUrlE + '" method="POST" name="fileDownload" id="fileDownload" target="_blank"></form>'); $('<input type="text" name="fileName" value="' + fileName + '">').appendTo(form); $(form).appendTo('body'); form.submit();//表单提交 $(form).remove(); document.characterSet = 'UTF-8'; document.charset = 'UTF-8';