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();
  }
 }
相關文章
相關標籤/搜索