C# 一般处理程序下载文件

时间:2023-02-20 19:26:43

利用一般处理程序下载文件,会在很多时候用到,但是,这是一条不归路啊,路上各种坑,不是乱码就是下载不下来。同样,今天我也踩上了这颗雷。还好,我是排雷兵,一样一样的排除

C# code

 //文件下载
        public void downloadfile(HttpContext context, string s_fileName)
        {
            string path = s_fileName;
            System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
            context.Response.Clear();
            context.Response.Charset = "UTF-8";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.AddHeader("Content-Type", "application/octet-stream");
            // 添加头信息,为"文件下载/另存为"对话框指定默认文件名,设定编码为UTF8,防止中文文件名出现乱码
            context.Response.AddHeader("Content-Disposition","attachment; filename="+ System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
            // 添加头信息,指定文件大小,让浏览器能够显示下载进度
            context.Response.AddHeader("Content-Length", file.Length.ToString());
            //// 指定返回的是一个不能被客户端读取的流,必须被下载
            context.Response.ContentType = "application/ms-excel";
            // 把文件流发送到客户端
            context.Response.WriteFile(file.FullName);
            // 停止页面的执行
            context.Response.End();
        }

注意:html页面一定不能是用ajax去请求一般处理程序,否则累死也实现不了下载,他会永远给你弹出一个框,一面一堆乱码

一定要同<a href="....../a.ashx">下载</a>这样的请求方式才可以,需要传参的话,直接在后面拼上就行

这样,轻轻松松搞定