asp.net 文件下载时,出现非法路径解决方案

来源:互联网 发布:交换机端口安全配置 编辑:程序博客网 时间:2024/06/05 12:02

问题原因:asp.net 页面之间传递中文时,编码转换出错,所以会出现该情况。

 

思路:可以用Server.EncodeURl ,Server.DecodeURl的属性编码和解码

 

关键代码

 

在下载连接上将url进行编码:

 

public string EncodeURL(string s)    {        string path = Server.UrlEncode(s);        return string.Format("Download.aspx?path={0}", path);    }


 

在处理下载的页面,对url进行解码:

  Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码                string filePath = Request.QueryString["path"].ToString();                filePath = Server.UrlDecode(filePath);                FileInfo file = new FileInfo(filePath);                if (file.Exists)                {                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码                       Response.AddHeader("Content-length", file.Length.ToString());                    Response.ContentType = "appliction/octet-stream";                    Response.WriteFile(file.FullName);                    Response.End();                }                else                {                    Response.Write("<font color='#ff0000'>您要下载的报表文件不存在,请联系管理员。</font>");                }


 

以上给出关键代码,供大家参考。

原创粉丝点击