真爱无限的知识驿站

学习积累技术经验,提升自身能力

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();
        }
 

 

 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-BlogPHP 1.7.3

Copyright 2024-2027 pukuimin Rights Reserved.
粤ICP备17100155号