文件下载名称出现乱码问题

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”);

        // name.getBytes(“UTF-8”)处理      safari的乱码问题
        byte[] bytes = userAgent.contains(“MSIE”) ? name.getBytes() : name.getBytes(“UTF-8”);
        name = new String(bytes, “ISO-8859-1”); // 各浏览器基本都支持ISO编码

        // 文件名外的双引号处理firefox的空格截断问题
        response.setHeader(“Content-disposition”, String.format(“attachment; filename=\”%s\””, name));
        // codes..
        }
}

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

    原文作者:天行健的程序员
    原文地址: https://blog.csdn.net/m0_37601917/article/details/89226738
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞