文件下载中文文件名乱码(转)

B/S应用中,下载一个附件保存时,中文文件名会乱码,在实际开发中经常遇到,现贴出C#和JAVA的解决方法:

C#:

Response.AppendHeader("Content-Disposition", "attachment;filename=" + Tools.toUtf8String(result));

 

其中用到的转换方法:

 1public static String toUtf8String(String s)
 2        {
 3            StringBuilder sb = new StringBuilder();
 4            for (int i=0;i<s.Length;i++)
 5            {
 6                char c = s[i];
 7                if (c >= 0 && c <= 255)
 8                {
 9                    sb.Append(c);
10                }

11                else
12                {
13                    byte[] b;
14                    try
15                    {
16                     b = Encoding.UTF8.GetBytes(c.ToString());
17                    }

18                    catch (Exception ex)
19                    {
20                        b = new byte[0];
21                    }

22                    for (int j = 0; j < b.Length; j++)
23                    {
24                        int k = b[j];
25                        if (k < 0) k += 256;
26                       
27                        sb.Append("%" + Convert.ToString(k,16).ToUpper());
28                    }

29                }

30            }

31            return sb.ToString();
32        }

33
34

 

JAVA:

resp.addHeader("Content-Disposition","attachment;filename=" + Tools.toUtf8String(m_entityIndex.m_sName) + ".xls");

其中用到的转换方法:

public static String toUtf8String(String s) {
        StringBuffer sb 
= new StringBuffer();
        
for (int i=0;i<s.length();i++{
            
char c = s.charAt(i);
            
if (c >= 0 && c <= 255{
                sb.append(c);
            }
 else {
                
byte[] b;
                
try {
                 b 
= new Character(c).toString().getBytes("utf-8");
                    
//b = Character.toString(c).getBytes("utf-8");
                }
 catch (Exception ex) {
                    System.out.println(ex);
                    b 
= new byte[0];
                }

                
for (int j = 0; j < b.length; j++{
                    
int k = b[j];
                    
if (k < 0) k += 256;
                    sb.append(
"%" + Integer.toHexString(k).
                    toUpperCase());
                }

            }

        }

        
return sb.toString();
    }


posted on 2009-01-22 15:15 jumliang 阅读(551) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2009年1月>
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

常用链接

留言簿(1)

随笔档案(4)

搜索

最新评论

阅读排行榜

评论排行榜