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下均测试通过。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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

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

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

  修改为gbk后问题解决。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄