Java 下载文件名乱码

java web应用文件下载(包括中文文件名乱码处理)

标签: javawebstringnullbyteie
        [Java]  view plain  copy
 print ?
  1.  Java web下载文件功能的确很简单。如下代码片段  
[Java]  view plain  copy
 
 print ?
  1. String fileName ="....";  
  2. response.setHeader("Content-disposition","attachment; filename="+fileName);  
  3. //response.setContentType("application/ms-word");  
  4.   
  5. BufferedInputStream bis = null;  
  6. BufferedOutputStream bos = null;  
  7.     try {  
  8.         bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("" + fileName)));  
  9.         bos = new BufferedOutputStream(response.getOutputStream());  
  10.   
  11.         byte[] buff = new byte[2048];  
  12.         int bytesRead;  
  13.   
  14.         while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  15.             bos.write(buff,0,bytesRead);  
  16.         }  
  17.   
  18.     } catch(final IOException e) {  
  19.         System.out.println ( "IOException." + e );  
  20.   
  21.     } finally {  
  22.         if (bis != null)  
  23.             bis.close();  
  24.         if (bos != null)  
  25.             bos.close();  
  26.     }  

如上所示,已经可以完成下载的功能。不过如果我们使用中文文件名,那么这段代码便会出错,解决办法有多种方式,如下:

 第一种: 设置  response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));这里将文件名编码成UTF-8的格式,就不会出现URL出错了。IE6下注意中文文字不能超过超过17个。

 第二种:设置response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );将中文名编码为ISO8859-1的方式。不过该编码只支持简体中文.

按照上诉方式,可以综合一下两种方式解决绝大部分中文问题。

 fileName = URLEncoder.encode(fileNameSrc,"UTF-8");

if(fileName.length()>150)//解决IE 6.0 bug

      fileName=new String(fileNameSrc.getBytes("GBK"),"ISO-8859-1");

response.setHeader( "Content-Disposition", "attachment;filename="  + fileName);

猜你喜欢

转载自aiyan2001.iteye.com/blog/2292381