标签:
B/S应用中,下载一个附件保存时,中文文件名会乱码,在实际开发中经常遇到,现贴出C#和JAVA的解决方法:
C#:
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Tools.toUtf8String(result));
其中用到的转换方法:
public static string ToUtf8String(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c >= 0 && c <= 255) { sb.Append(c); } else { byte[] b; try { b = Encoding.UTF8.GetBytes(c.ToString()); } catch (Exception ex) { b = new byte[0]; } for (int j = 0; j < b.Length; j++) { int k = b[j]; if (k < 0) k += 256; sb.Append("%" + Convert.ToString(k, 16).ToUpper()); } } } return sb.ToString(); }
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(); }
标签:
原文地址:http://www.cnblogs.com/hnsongbiao/p/4202951.html