当前位置: 代码迷 >> Web前端 >> 解决不同浏览器下中文文件名的上载乱码有关问题
  详细解决方案

解决不同浏览器下中文文件名的上载乱码有关问题

热度:116   发布时间:2012-09-11 10:49:03.0
解决不同浏览器上中文文件名的下载乱码问题

目前,我们的U盘和Mail中对含有中文文件名的下载处理都不是太好

?

在某些浏览器下,下载显示的文件名是乱码

?

我又顺便看了一下其他各邮箱和网盘的处理,只有QQ处理的比较好

?

现在时基本上每个浏览器都能正常显示中文的文件名

?

花了一些时间对IE,Firefox,Opera,Chrome,Safari这几个浏览器进行了测试

?

总结了一下,各浏览器能正确识别的编码格式,只要按照这样的编码来设置对应的Content-Disposition

?

那么应该就不会出现中文文件名的乱码问题了

?

?

?

首先,Content-Disposition值可以有以下几种编码格式

?

1. 直接urlencode:

?

?? ?Content-Disposition: attachment; filename="struts2.0%E4%B8%AD%E6%96%87%E6%95%99%E7%A8%8B.chm"

?

2. Base64编码:

?

?? ?Content-Disposition: attachment; filename="=?UTF8?B?c3RydXRzMi4w5Lit5paH5pWZ56iLLmNobQ==?="

?

3. RFC2231 规定的标准:

?

?? ?Content-Disposition: attachment; filename*=UTF-8''%E5%9B%9E%E6%89%A7.msg

?

4. 直接ISO编码的文件名:

?

?? ?Content-Disposition: attachment;filename="测试.txt"

?

然后,各浏览器支持的对应编码格式为:

?

1. ?IE浏览器,采用URLEncoder编码

?

2. ?Opera浏览器,采用filename*方式

?

3. ?Safari浏览器,采用ISO编码的中文输出

?

4. ?Chrome浏览器,采用Base64编码或ISO编码的中文输出

?

5. ?FireFox浏览器,采用Base64或filename*或ISO编码的中文输出

?

?

?

对应的Java代码如下:

?

折叠 复制代码

?

  1. new_filename?=?URLEncoder.encode(filename,? "UTF8" );??
  2. ?

  3. //?如果没有UA,则默认使用IE的方式进行编码,因为毕竟IE还是占多数的 ??
  4. ?

  5. rtn?=?"filename="" ?+?new_filename?+? """ ;??
  6. ?

  7. if ?(userAgent?!=? null )??
  8. ?

  9. {??
  10. ?

  11. ????userAgent?=?userAgent.toLowerCase();??
  12. ?

  13. ????//?IE浏览器,只能采用URLEncoder编码 ??
  14. ?

  15. ????if ?(userAgent.indexOf( "msie" )?!=?- 1 )??
  16. ?

  17. ????{??
  18. ?

  19. ????????rtn?=?"filename="" ?+?new_filename?+? """ ;??
  20. ?

  21. ????}??
  22. ?

  23. ????//?Opera浏览器只能采用filename* ??
  24. ?

  25. ????else ? if ?(userAgent.indexOf( "opera" )?!=?- 1 )??
  26. ?

  27. ????{??
  28. ?

  29. ????????rtn?=?"filename*=UTF-8''" ?+?new_filename;??
  30. ?

  31. ????}??
  32. ?

  33. ????//?Safari浏览器,只能采用ISO编码的中文输出 ??
  34. ?

  35. ????else ? if ?(userAgent.indexOf( "safari" )?!=?- 1 ?)??
  36. ?

  37. ????{??
  38. ?

  39. ????????rtn?=?"filename="" ?+? new ?String(filename.getBytes( "UTF-8" ), "ISO8859-1" )?+? """ ;??
  40. ?

  41. ????}??
  42. ?

  43. ????//?Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出 ??
  44. ?

  45. ????else ? if ?(userAgent.indexOf( "applewebkit" )?!=?- 1 ?)??
  46. ?

  47. ????{??
  48. ?

  49. ????????new_filename?=?MimeUtility.encodeText(filename,?"UTF8" ,? "B" );??
  50. ?

  51. ????????rtn?=?"filename="" ?+?new_filename?+? """ ;??
  52. ?

  53. ????}??
  54. ?

  55. ????//?FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出 ??
  56. ?

  57. ????else ? if ?(u
    serAgent.indexOf(
    "mozilla" )?!=?- 1 )??
  58. ?

  59. ????{??
  60. ?

  61. ????????rtn?=?"filename*=UTF-8''" ?+?new_filename;??
  62. ?

  63. ????}??
  64. ?

  65. }??

?

?

目前,我测试的情况,在几个浏览器上都能正常输入中文文件名

?

但,也许浏览器不同版本,可能还会有乱码的情况…..
  相关解决方案