我在本地开发环境(Tomcat5.5)测试时能正常显示附件中的内容,但是发布到服务器上,用IE打开附件能正常区分出是什么类型文件,但是打开就是乱码,代码如下:
<%@page pageEncoding="UTF-8"%>
<%@page language="java" import="java.util.*,java.io.*,java.net.*"%>  
  <%      .......
      
      response.setContentType(file.getString("fileType"));   //fileType表示文件类型
      response.setHeader("Content-Disposition", "attachment;filename=\"" +  new String(file.getString("fileName").getBytes("gb2312"), "ISO8859-1" )  + "\"");   
      OutputStream output = response.getOutputStream();
  ByteArrayInputStream in = new ByteArrayInputStream(bytes); 
      try{        
     int i;   
     byte[] b = new byte[1024];
      while((i=in.read(b)) != -1){
       output.write(b, 0, i);
      }  
      output.flush();
      out.clear();
  out = pageContext.pushBody();
   }catch(java.io.IOException e){   
 System.out.println("Error!");
 e.printStackTrace();  
   } finally {
 if (in != null) {
in.close();
in = null;
 }
if (output != null) {
output.close();
output = null;
 }
}   
  %>

解决方案 »

  1.   

    ByteArrayInputStream in = new ByteArrayInputStream(bytes); 这个 bytes是个啥东西啊?
    如果是文件过来的,为何不直接操作输入流呢?不要再封装了。
      

  2.   

    byte[] bytes//是传过来的文件字节流数组,
    为啥会显示乱码?
      

  3.   

    <%@page language="java" import="java.io.*"%>  
      <%
       ....
          //bytes是文件字节流
      String file_type = (String)file.getString("fileType");
          response.setContentType(file_type);   
          System.out.println("---" + file_type + "---" + bytes.length);
          response.setHeader("Content-Disposition", "attachment;filename=\"" +  new String(file.getString("fileName").getBytes("gb2312"), "ISO8859-1" )  + "\"");   
          OutputStream output = response.getOutputStream();
          try{               output.write(bytes); //bytes是文件字节流
          output.flush();
          out.clear();
      out = pageContext.pushBody();
       }catch(java.io.IOException e){   
     System.out.println("Error!");
     e.printStackTrace();  
       } finally {
    if (output != null) {
    output.close();
    output = null;
     }
    }   
      %>
      

  4.   

    打开txt时,txt文件中会多一行空,显示在第一行;
    打开zip、pdf没问题,word,excel不行
      

  5.   

    异常信息:
    java.io.IOException: response already committed
    at weblogic.servlet.jsp.JspWriterImpl.clear(JspWriterImpl.java:56)
    at jsp_servlet._mpcommon.__show_file._jspService(__show_file.java:107)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42)