JSP文件下载时文件名在ie和firefox下面文件名不一致极其超链接中文乱码的问题的改进

response.setContentType("application/octet-stream;charset=UTF-8");
fileName=java.net.URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
此时在ie下面点击文件下载的时候能够正确显示中文名称但是此时在firefox下面却显示1_%E4%B8%AD%E6%96%87%E6%96%87%E4%BB%B6123.doc然后我又试了另一种方案


response.setContentType("application/octet-stream;charset=UTF-8");
fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
此时在ie下面下载的时候弹chu的文件名是乱码;而在firefox下面却正确显示1_中文文件XXX.doc。

我想要的是不管是ie还是firefox都正确显示1_中文XX.doc,不知道大家有没有遇到过类似的问题,解决之道是什么?
也许判断浏览器类型来进行不同的处理会是一种解决方案,但是这是一种个人觉得迫不得已的解决方案。

=================工具类=============================
package com.jub.jubweb1.JTool;

import javax.servlet.http.HttpServletRequest;

public  class  JToolWeb {
 
 //文件下载时文件名在ie和firefox下面表现不一致问题,乱码
 public static String processFileName(HttpServletRequest request,String fileNames){
  String codedfilename = null;
  try{
  String agent =request.getHeader("USER-AGENT");
  if(null != agent && -1 != agent.indexOf("MSIE")){//ie
  String prefix = fileNames.lastIndexOf(".")!=-1?fileNames.substring(0,fileNames.lastIndexOf(".")):fileNames;
  String extension = fileNames.lastIndexOf(".")!=-1?fileNames.substring(fileNames.lastIndexOf(".")):"";
  String name = java.net.URLEncoder.encode(fileNames, "UTF8"); 
  if(name.lastIndexOf("%0A")!=-1){
  name = name.substring(0,name.length()-3);
  }
  int limit = 150 - extension.length();//文件名超过 17 个中文字符,在 IE 下会有问题
  if (name.length() > limit) {
   name = java.net.URLEncoder.encode(prefix.substring(0, Math.min(prefix.length(), limit / 9)), "UTF-8"); 
   if(name.lastIndexOf("%0A")!=-1){
   name = name.substring(0,name.length()-3);
   }
  }else{
   return name;
  }
  codedfilename = name + extension;  
  } else if (null != agent && -1 != agent.indexOf("Mozilla")) {//火狐
  codedfilename = "=?UTF-8?B?"+(new String(org.apache.commons.codec.binary.Base64.encodeBase64(fileNames.getBytes("UTF-8"))))+"?=";
  }else {
  codedfilename = fileNames;
  }
  }catch(Exception e){
   e.printStackTrace();
  }
  return codedfilename;
 }
}

=================================jsp============================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8;" import="java.io.*,com.jub.jubweb1.JTool.*" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载</title>
</head>
<body>
<%
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
//关于文件下载时采用文件流输出的方式处理: 
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个; 
///response.reset();//可以加也可以不加  ,注意加了之后tomcate需要配置UTF-8否则乱码
String filePath=request.getSession().getServletContext().getRealPath("")+request.getParameter("path");
File file = new File(filePath);
if (!file.exists() || file.isDirectory()) {
 filePath=new String(filePath.getBytes("iso-8859-1"),"UTF-8");//防止tomcate编码不一
 file = new File(filePath);
 if (!file.exists() || file.isDirectory()){//二次验证
 %>
 <script type="text/javascript" charset="UTF-8">
  alert('抱歉,资源正在维护中,请稍后再试,如果有需要请联系我们的客服,谢谢!');
 </script>
 <%
 System.out.print(filePath);
 return;
 }
}
String fileName=filePath.substring(filePath.lastIndexOf("\\")+1,filePath.length());
System.out.print(fileName);
System.out.print(filePath);
//filename=new String(filename.getBytes("iso8859-1"),"gb2312");//使用超链接解决中文乱码
// 设置响应头和下载保存的文件名
response.setContentType("application/x-download"); 
//response.addHeader("Content-Disposition","attachment;filename=" +new String(fileName.getBytes("gb2312"),"iso8859-1"));//解决中文乱码
//response.addHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(fileName,"utf-8"));//解决中文乱码
String t=JToolWeb.processFileName(request,fileName);
response.addHeader("Content-Disposition","attachment;filename="+t);//解决中文乱码
System.out.println(t+"--------");
response.setContentLength((int)file.length());
java.io.OutputStream outp = null;
java.io.FileInputStream in = null; 
try 

outp = response.getOutputStream(); 
in = new FileInputStream(file); 
 
byte[] b = new byte[1024]; 
int i = 0; 
 
while((i = in.read(b)) > 0) 

outp.write(b, 0, i); 

// 
outp.flush(); 
//要加以下两句话,否则会报错 
//java.lang.IllegalStateException: getOutputStream() has already been called for //this response   
out.clear(); 
out = pageContext.pushBody(); 

catch(Exception e) 

System.out.println("Error!"); 
e.printStackTrace(); 

finally 

if(in != null) 

in.close(); 
in = null; 

//这里不能关闭   
//if(outp != null) 
//{ 
//outp.close(); 
//outp = null; 
//} 
}
%>
</body>
</html>

 

===========================jsp==================================
 <a href='javascript:subFrom("/jubweb1/down/down_stream.jsp","\\download\\erp\\行政管理手册.doc")'>下载</a>
 <!--下载使用的表单-->
  <form id="down_frm" name="down_frm" method="post" target="down_if"  style="display:none;">
  <input type="hidden" id="path" name="path"/>
  </form>
  <iframe  id="down_if" name="down_if" style="display:none;"></iframe><!--下载使用的iframe-->
  <script>
  
  function subFrom(url,param){
   $("#path").attr("value",param);
   $("#down_frm").attr("action",url);
   $("#down_frm").attr("method","post");
   $("#down_frm").submit();
     }
  </script>

你可能感兴趣的:(firefox)