兼容各浏览器的文件下载时中文名称乱码的解决方案


public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// codes..
String name = "中文名 带空格 的测试文件.txt";
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? name.getBytes() : name.getBytes("UTF-8"); // name.getBytes("UTF-8")处理safari的乱码问题
name = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", name)); // 文件名外的双引号处理firefox的空格截断问题
// codes..
}
}

这段代码处理了文件下载时不同浏览器解析中文文件名所出现的乱码问题和firefox的空格截断问题,在IE9, chrome, opera, safari, firefox下均测试通过。

来源:https://f0rb.iteye.com/blog/1308579

    但是没有解决我的ie9下载时的乱码问题,做了一步修改:

response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));

  修改为gbk后问题解决。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM