当前位置: 代码迷 >> Web前端 >> 上载中文件名乱码解决方案
  详细解决方案

上载中文件名乱码解决方案

热度:89   发布时间:2012-11-22 00:16:41.0
下载中文件名乱码解决方案

有很多在bs开发中遇到过下载问题,在这里我讲一下我工作中遇到下载文件名为乱码的情况:

一般在下载的时候,我们都会加上

response.setHeader("Content-Disposition",??"attachment; filename=" + filename);

这句话,目的是让浏览器能正确解析文件名

如果在你几经努力的转换filename(文件名)也不管用的话,可以试一下我的方法

java 代码
  1. public?static?String?toUtf8String(String?source)?{ ??
  2. ??StringBuffer?sb?=?new?StringBuffer(); ??
  3. ??for?(int?i?=?0;?i?<?source.length();?i++)?{ ??
  4. ???char?c?=?source.charAt(i); ??
  5. ???if?(c?>=?0?&&?c?<=?255)?{ ??
  6. ????sb.append(c); ??
  7. ???}?else?{ ??
  8. ????byte[]?b; ??
  9. ????try?{ ??
  10. ?????b?=?Character.toString(c).getBytes("UTF-8"); ??
  11. ????}?catch?(Exception?ex)?{ ??
  12. ?????System.out.println(ex); ??
  13. ?????b?=?new?byte[0]; ??
  14. ????} ??
  15. ????for?(int?j?=?0;?j?<?b.length;?j++)?{ ??
  16. ?????int?k?=?b[j]; ??
  17. ?????if?(k?<?0)?{ ??
  18. ??????k?+=?256; ??
  19. ?????} ??
  20. ?????sb.append("%"?+?Integer.toHexString(k).toUpperCase()); ??
  21. ????} ??
  22. ???} ??
  23. ??} ??
  24. ??return?sb.toString(); ??
  25. ?} ??
  26. ??

是让文件名都转成UTF-8格式

希望这个方法能解决你们的难题

?

  相关解决方案