bobowu

文件下载程序中发现的文件名过长的问题

居然发现文件名编码后长度超过155就会不能正确显示和下载,最后只好找了这样一个折中的方法,截短了
下面是那里的代码。后来查看了RFC 2183 中的说明,有一句这样的NOTE ON PARAMETER VALUE LENGHTS: A short (length <= 78 characters),这个应该是官方的解释吧,不过我用155在IE中没有问题,不过可能是IE另外放宽了限制吧。


今天发现下面的那个155也是不可靠的,今天有个过长的文件中间有个“.”就出问题了,下载时能常显示文件名,下载文件也没有问题,但下载下来后一看文件名居然变成了那些编码的字符串,后来把155改成154或做个检测如果遇到“.”就减少这个数字就不会有问题。

 1/// <summary>
 2  /// 下载附件。
 3  /// </summary>
 4  /// <param name="fileName">文件名</param>
 5  /// <param name="path">文件路径</param>

 6  public static void DownLoadFileAttachment(string fileName , string path)
 7  {
 8   if (System.IO.File.Exists(path))
 9   {
10    try
11    {
12     fileName  = fileName.Trim();
13
14     for (int  i = 0 ; i < System.IO.Path.InvalidPathChars.Length ; i ++)
15     {
16      fileName = fileName.Trim().Replace(System.IO.Path.InvalidPathChars[i].ToString() , string.Empty);
17     }

18
19     fileName  = fileName.Replace(System.IO.Path.PathSeparator.ToString() , string.Empty);
20     
21     int maxLength = 155;
22
23     int length  = HttpUtility.UrlEncode(fileName).Length;
24     while (length > maxLength)
25     {
26      int index = fileName.LastIndexOf(".");
27      if (index > 0)
28      {
29       fileName = fileName.Substring(0 , index - 1+ fileName.Substring(index);
30      }

31      else
32      {
33       fileName = fileName.Substring(0 , fileName.Length - 1);
34      }

35      length  = HttpUtility.UrlEncode(fileName).Length;
36     }

37
38     System.IO.FileInfo file = new System.IO.FileInfo(path); 
39     HttpContext.Current.Response.Clear(); 
40     HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment; filename=" + HttpUtility.UrlEncode(fileName)); 
41     HttpContext.Current.Response.AppendHeader("Content-Length", file.Length.ToString()); 
42     HttpContext.Current.Response.ContentType = "application/octet-stream"
43     HttpContext.Current.Response.WriteFile(file.FullName); 
44     HttpContext.Current.Response.End(); 
45    }

46    catch
47    {
48    }

49   }

50   else
51   {
52    HttpContext.Current.Response.Clear();
53    DisplayNoFileMessage();
54    HttpContext.Current.Response.End();
55   }

56  }

57

posted on 2005-08-14 11:30  Bobo  阅读(3078)  评论(0编辑  收藏  举报

导航