servlet 下载文件名 乱码

servlet下载文件,中文名文件如何正常下载。通过亲自试验,项目使用。记下来。html

测试了三个浏览器 IE 9 , Chrome 36 , FF 32java

结论是浏览器

    IE 须要使用URLEncoder.encode("UTF-8")编码中文文件名,app

    FF, Chrome 使用new String(filename.getBytes("UTF-8"),"ISO-8859-1");测试

验证的代码以下,一个Servlet ,要下载的文件在classpath下this

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html;charset=UTF-8");
  String path = "中文名测试2014-10-14.xls";
  try {
   InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);//WEB应用
   System.out.println(is);
   ServletOutputStream os = response.getOutputStream();
   String filename = path;
   //先设置返回结果类型  
     //返回的文件名设置    
   //验证1:=========使用new String()
    //filename  = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
        //IE    Content-Disposition attachment;filename=中文名测试2014-10-14.xls ,
             //下载框是乱码
     //Chrome  Content-Disposition:attachment;filename=云资源管理平台报表2014-10-14.xls
         //下载框正常
      //FF Content-Disposition attachment;filename=云资源管理平台报表2014-10-14.xls
       //下载框正常
     
    //验证2:========使用URLEncoder.encode URL编码
     //filename = URLEncoder.encode(filename, "UTF-8");
       //IE     Content-Disposition attachment;filename=%E4%BA%91%E8%B5%84%E6%BA%90%E7%AE%A1%E7%90%86%E5%B9%B3%E5%8F%B0%E6%8A%A5%E8%A1%A82014-10-14.xls
       //下载框是正常
     //Chrome  Content-Disposition:attachment;filename=%E4%BA%91%E8%B5%84%E6%BA%90%E7%AE%A1%E7%90%86%E5%B9%B3%E5%8F%B0%E6%8A%A5%E8%A1%A82014-10-14.xls
       //下载框正常
     //FF Content-Disposition attachment;filename=%E4%BA%91%E8%B5%84%E6%BA%90%E7%AE%A1%E7%90%86%E5%B9%B3%E5%8F%B0%E6%8A%A5%E8%A1%A82014-10-14.xls
       //下载框文件名同响应头文件名
      
          //3.结论:----------------- 
    //IE 使用URLEncoder.encode ,FF ,Chrome 使用new String()
    String ua = request.getHeader("User-Agent"); 
    if(ua.indexOf("MSIE") != -1){
     //IE 
     filename = URLEncoder.encode(filename, "UTF-8");
    }else{
      // Chrome , Forefox 
     //Chrome浏览器 响应头 äº‘资源管理平台报表2014-10-14.xls
     //FF 响应头 Content-Disposition attachment;filename=云资源管理平台报表2014-10-14.xls
     filename  = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
    }
     
   response.setHeader("Content-Disposition", "attachment;filename=" + filename);
   //response.setHeader("Content-Length", "373590");//byte单位 373KB
 373K   response.setContentType("application/vnd.ms-excel");
   byte[] buffer = new byte[1024];
   int len = 0;
   while((len = is.read(buffer)) !=-1){
    os.write(buffer, 0, len);
   }
   
   os.flush();
   os.close();
   is.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
相关文章
相关标签/搜索