struts2 下載 解決IE,火狐下載亂碼

one:

Struts.xml

<result name="success" type="stream"><!-- ;charset=UTF-8  ;charset=ISO-8859-1-->
    <param name="contentType">application/octet-stream</param>  
    <param name="contentDisposition">attachment;filename=${fileName}</param>
    <param name="inputName">fileinputstream</param>
    <param name="bufferSize">4096</param>
   </result>

two:

 private FileInputStream fileinputstream;

 private String fileName;

/**
  * 下载文件
  */
 public InputStream getFileinputstream(){
//  ServletActionContext.getResponse().setContentType("application/octet-stream;charset=UTF-8");
  try {


   String s=(String) Constants.SIDECODE_LIST[Constants.SIDECODE_IN_STATE][2];
   String url=this.getFileUrl().replace("http://www.jiwu.com/", s);  //這裡你可以自己配置路徑


   fileinputstream = new FileInputStream(new File(url));
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return fileinputstream;
 }

 public void setFileinputstream(FileInputStream fileinputstream) {
  this.fileinputstream = fileinputstream;
 }

/**
  * 防止IE,火狐乱码
  * @return
  */

 public String getFileName() {
  if(fileName!=null){
   try {
    HttpServletRequest request = ServletActionContext.getRequest();  
          String Agent = request.getHeader("User-Agent");  
          if (null != Agent) {  
              Agent = Agent.toLowerCase();  
              if (Agent.indexOf("firefox") != -1) {  
               fileName = new String(fileName.getBytes(),"ISO-8859-1");  
//               fileName = StringUtils.replace(fileName, " ", "%20");
              } else if (Agent.indexOf("msie") != -1) {  
               fileName = java.net.URLEncoder.encode(fileName,"UTF-8"); 
               fileName = StringUtils.replace(fileName, "+", "%20");
              } else {  
               fileName = java.net.URLEncoder.encode(fileName,"UTF-8");  
               fileName = StringUtils.replace(fileName, "+", "%20");
              }  
          } 

   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
   return fileName;
  }
  return "";
 }
 public void setFileName(String fileName) {
  this.fileName = fileName;
 }

你可能感兴趣的:(struts2,IE,下载,乱码,火狐)