居然发现文件名编码后长度超过155就会不能正确显示和下载,最后只好找了这样一个折中的方法,截短了
下面是那里的代码
/// <summary>
/// 下载附件。
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="path">文件路径</param>
public static void DownLoadFileAttachment(string fileName , string path)
{
if (System.IO.File.Exists(path))
{
try
{
fileName = fileName.Trim();
for (int i = 0 ; i < System.IO.Path.InvalidPathChars.Length ; i ++)
{
fileName = fileName.Trim().Replace(System.IO.Path.InvalidPathChars[i].ToString() , string.Empty);
}
fileName = fileName.Replace(System.IO.Path.PathSeparator.ToString() , string.Empty);
int maxLength = 155;
int length = HttpUtility.UrlEncode(fileName).Length;
while (length > maxLength)
{
int index = fileName.LastIndexOf(".");
if (index > 0)
{
fileName = fileName.Substring(0 , index - 1) + fileName.Substring(index);
}
else
{
fileName = fileName.Substring(0 , fileName.Length - 1);
}
length = HttpUtility.UrlEncode(fileName).Length;
}
System.IO.FileInfo file = new System.IO.FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
HttpContext.Current.Response.AppendHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.End();
}
catch
{
}
}
else
{
HttpContext.Current.Response.Clear();
DisplayNoFileMessage();
HttpContext.Current.Response.End();
}
}
本文地址:http://com.8s8s.com/it/it42895.htm