zoukankan      html  css  js  c++  java
  • .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;
            }
        }
    View Code

    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';
    View Code
  • 相关阅读:
    Delphi 的RTTI机制浅探3(超长,很不错)
    关于跨进程使用回调函数的研究:以跨进程获取Richedit中RTF流为例(在Delphi 初始化每一个TWinControl 对象时,将会在窗体 的属性(PropData)中加入一些标志,DLL的HInstance的值与HOST 进程的HInstance并不一致)
    获得QQ聊天输入框中的内容
    使用Jenkins来构建Docker容器
    各种排序算法汇总
    ASP.NET Web API和ASP.NET Web MVC中使用Ninject
    s性能优化方面的小知识
    算法时间复杂度的计算
    js模块开发
    NET Framework 4.5 五个新特性
  • 原文地址:https://www.cnblogs.com/zhchsh/p/5546052.html
Copyright © 2011-2022 走看看