膛线都磨平了
2019-07-10 01:18
采纳率: 16.7%
浏览 912

servlet 下载文件时文件名中文乱码问题一直解决不了

jsp页面通过超链标签下载文件,文件名包含中文时,下载乱码,英文和数字可以正常下载,根据网上的方法试了很多次还是解决不了,困扰一天了,现在是凌晨1点这个问题搞得我睡不着,各位老哥帮小弟看看是
哪里错了图片说明页面编码设置utf_8
图片说明下载链接

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
           response.setCharacterEncoding("UTF-8");
        EbizCompany company = (EbizCompany) request.getSession().getAttribute("currentCompany");
        //String file = new String(request.getParameter("file").getBytes("ISO-8859-1"),"UTF-8");
        String fileName = request.getParameter("file"); //客户端传递的需要下载的文件名
        fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
        System.out.println("filename  "+fileName);
        //获得请求头中的User-Agent
                String agent = request.getHeader("User-Agent");
               //根据不同浏览器进行不同的编码
                 String fileNameEncoder = "";
                if (agent.contains("MSIE")) {
                 // IE浏览器
               fileNameEncoder = URLEncoder.encode(fileName, "utf-8");
                 fileNameEncoder = fileNameEncoder.replace("+", " ");
                 } else if (agent.contains("Firefox")) {
                     // 火狐浏览器
                    BASE64Encoder base64Encoder = new BASE64Encoder();
                    fileNameEncoder = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
                } else {
                    // 其它浏览器
                     fileNameEncoder = URLEncoder.encode(fileName, "utf-8");                
             }
                //客户端通过文件的MIME区分下载的文件的类型
                response.setContentType(this.getServletContext().getMimeType(fileName));
                 //告诉客户端不要直接解析该文件,而是以附件的形式打开(下载)            客户端默认对名字进行解码
                response.setHeader("Content-Disposition", "attachment;filename=" + fileNameEncoder);
        String time=Integer.toString(GeneralMethod.getYear(System.currentTimeMillis()))+"\\"+Integer.toString(GeneralMethod.getMonth(System.currentTimeMillis()));
        String path = Constant.FilePath + "\\" + company.companyName+"\\"+time+"\\"+fileName;
        FileInputStream fis = new FileInputStream(path);
        response.setContentType("multipart/form-data");  
        ServletOutputStream out = response.getOutputStream();
        byte[] bt = new byte[1024];
        int length = 0;
        while((length=fis.read(bt))!=-1){
            out.write(bt,0,length);
        }
        out.close();

        }
```  ![图片说明](https://img-ask.csdn.net/upload/201907/10/1562692854_226734.png)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 萧萧风 2019-07-10 10:14
    已采纳

    fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); //这一步注释掉试试

    点赞 评论
  • KiterCher 2019-07-10 10:21

    response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
    对文件名格式化。 %s 对匹配的字符串进行格式化,匹配的值为format的第三个参数fileName

    点赞 评论