ashx灵活处理文件下载问题

 

新建一般处理程序 ,改下面的函数:

        public void ProcessRequest(HttpContext context)
        {
            string filename;
            try
            {

                filename = context.Request["filename"].ToString();
            }
            catch
            {
                context.Response.Write("不正确的访问!");
                return;
            }

            string RealFile = context.Server.MapPath("~/Upload/files/" + filename);//真实存在的文件
            if (!System.IO.File.Exists(RealFile))
            {
                context.Response.Write("服务器上该文件已被删除或不存在!"); return;
            }
            context.Response.Buffer = true;
            context.Response.Clear();
            context.Response.ContentType = "application/download";
            string downFile=System.IO.Path.GetFileName(filename);//这里也可以随便取名
            string EncodeFileName = HttpUtility.UrlEncode(downFile, System.Text.Encoding.UTF8);//防止中文出现乱码
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + EncodeFileName + ";");
            context.Response.BinaryWrite(System.IO.File.ReadAllBytes(RealFile));//返回文件数据给客户端下载
            context.Response.Flush();
            context.Response.End();
        }
 

 

上一篇:mssql视图和触发器的操作


下一篇:中文代码示例之NW.js桌面应用开发初体验