Thinking

快乐编程,开心生活
posts - 21, comments - 27, trackbacks - 0, articles - -5
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

文件下载中的汉字编码问题

Posted on 2007-02-07 14:32 lixw 阅读(239) 评论(0)  编辑  收藏
 1 public   void  doDownLoad(HttpServletRequest request, HttpServletResponse response, 
 2             String absolutePath)  {
 3         
 4          // 设置响应头信息
 5         response.setContentType( " application/octet-stream;charset=UTF-8 " ); 
 6         log.debug( " GET:  "   +  absolutePath);
 7         
 8         String str  =  FilePathParseUtil.getFileNameByPath(absolutePath);
 9          // 调用自定义的编码函数,解决不同浏览器上对汉字编码的处理
10         str  =   this .encodeFileName(request, str) == null ? str: this .encodeFileName(request, str);
11          // 设置response头信息,从而显示正确的文件名,并弹出另存对话框
12         response.setHeader( " Content-Disposition " " attachment; filename= "  
13                  +  str);
14         OutputStream out  =   null ;
15          try {
16              // 从response得到输出流,从而向客户端写出文件
17             out  =  response.getOutputStream();
18         }
catch (IOException e) {
19             log.error( " output stream is null " );
20             e.printStackTrace();
21         }

22          this .doDownLoad(out, absolutePath);
23     }

24     
25      /**
26      * 根据不同浏览器对文件名进行编码
27      *  @param  request 客户端请求
28      *  @param  fileName 文件名
29      *  @return  编码后的文件名
30       */

31      public  String encodeFileName(HttpServletRequest request, String fileName) {   
32         String agent  =  request.getHeader( " USER-AGENT " );
33          try {
34              if  ( null   !=  agent  &&   - 1   !=  agent.indexOf( " MSIE " ))  {   
35                  return  URLEncoder.encode(fileName,  " UTF-8 " );   
36             }
else   if  ( null   !=  agent  &&   - 1   !=  agent.indexOf( " Mozilla " ))  {   
37                  return   " =?UTF-8?B? " +
38                          new  String(
39                                 Base64.encodeBase64(
40                                     fileName.getBytes( " UTF-8 " )
41                                 )
42                         )  +   " ?= " ;   
43             }
  else   {   
44                  return  fileName;   
45             }

46         }
catch (UnsupportedEncodingException e) {
47              return   null ;
48         }

49     }
  

只有注册用户登录后才能发表评论。


网站导航: