文件下载IE中文乱码问题
?
浏览器能正确识别的编码格式,只要按照这样的编码来设置对应的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编码的中文输出?
?
实例代码:
?
?
?
? ? ? ? ? ? ? ? String agent = request.getHeader("USER-AGENT");
? ? ? ? ? ? ? ? if(agent != null && agent.indexOf("MSIE") != -1) {
? ? ? ? ? ? ? ? ? ? fileName = URLEncoder.encode(fileName,"UTF8");
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? response.setContentType("application/octet-stream;charset=UTF-8");
? ? ? ? ? ? ? ? response.setHeader("Content-Disposition","attachment; filename="" + fileName +""");
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? FileCopyUtils.copy(new FileInputStream(file),response.getOutputStream());
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }