File   f   =   new   File("c:\\测试.xls");   
  FileInputStream   fin   =   new   FileInputStream(f);   
  response.setContentType("application/vnd.ms-excel;charset=GB2312");   
  response.setHeader("Content-Disposition",   "attachment;   filename=测试.xls");   
  OutputStream   output   =   response.getOutputStream();   
  byte[]   buf   =   new   byte[1024];   
  int   r   =   0;   
  while((r   =   fin.read(buf,   0,   buf.length))!=   -1)   {   
            output.write(buf,   0,   r);   
  }   
  fin.close();   
  output.close(); 
这段代码放在jsp中,点击jsp时,jsp中出现乱码,excel也没有下载到客户端

解决方案 »

  1.   

    给你一个源代码,希望给你有用:
    <%@ page import="java.io.*"%> 
    <%@ page contentType="text/html;charset=GBK"%>
    <%! 
    public String toUtf8String(String s) {
    StringBuffer sb = new StringBuffer(); 
     for (int i=0;i<s.length();i++) { 
       char c = s.charAt(i); 
        if (c >= 0 && c <= 255) { 
          sb.append(c); 
         } else { 
        byte[] b; 
        try { 
           b = Character.toString(c).getBytes("utf-8"); 
        } catch (Exception ex) { 
          System.out.println(ex); 
          b = new byte[0]; 
        } 
      for (int j = 0; j < b.length; j++) { 
         int k = b[j]; 
          if (k < 0) k += 256; 
            sb.append("%" + Integer.toHexString(k). 
            toUpperCase()); 
          } 
      } 

    System.out.println("sb:"+sb.toString());
    return sb.toString(); 

    %> 
    <% 
    request.setCharacterEncoding("GBK");
    //文件名
    String filename = request.getParameter("filenme");
    //服务器相关程序下的相对路径,完整路径:export/home/process/web/test/data/images
    String dirName=application.getRealPath("test/data/images"); 
    java.io.File strFile=null; 
    String strPath=dirName+System.getProperties().getProperty("file.separator")+filename; 
    System.out.println("生成图片路径:"+strPath);
      try{ 
         strFile=new java.io.File(strPath); 
       }catch(Exception e){ 
        e.printStackTrace(); 
       } 
     if (strFile!=null&&strFile.exists()&&strFile.isFile()) 
      { 
        long filelength = strFile.length(); 
    OutputStream outputStream = response.getOutputStream();
    InputStream inputStream = new FileInputStream(strPath);
        //设置输出的格式 
         response.reset(); 
         response.setContentType("application/x-msdownload"); 
         response.setContentLength((int)filelength); 
         response.addHeader("Content-Disposition","attachment; filename=\"" + toUtf8String(filename) + "\""); 
         //循环取出流中的数据 
         byte[] b = new byte[1024]; 
         int len=-1; 
         while((len=inputStream.read(b))!=-1){
       outputStream.write(b, 0, len);
     }
         outputStream.flush();
         outputStream.close();
         inputStream.close();
         outputStream = null;
     } 
    %>
      

  2.   

    用你toUtf8String这个方法处理后,还是出现乱码,你看我这个问题出在哪呢
      

  3.   

    首先先要把这个文件生成到web的目录下
    File   f   =   new   File(request.getRealPath()+"\\测试.xls");
    这样就可以通过ie访问这个文件了
    然后在web.xml里加 
      <mime-mapping>
        <extension>doc</extension>
        <mime-type>application/msword</mime-type>
      </mime-mapping>
      <mime-mapping>
        <extension>xls</extension>
        <mime-type>application/msexcel</mime-type>
      </mime-mapping>
    这样就可以正常打开word和excel了
      

  4.   

    iider 我是要下载到客户端不是在网上打开
      

  5.   

    文件下载篇 1、下载链接页面download.html 页面源码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>下载</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body><a href="jsp/do_download.jsp">点击下载</a></body></html>
     2、下载处理页面do_download.jsp do_download.jsp展示了如何利用jspSmartUpload组件来下载文件,从下面的源码中就可以看到,下载何其简单。 源码如下: 
    <%@ page contentType="text/html;charset=gb2312" import="com.jspsmart.upload.*" %><%               // 新建一个SmartUpload对象        SmartUpload su = new SmartUpload();               // 初始化        su.initialize(pageContext);               // 设定contentDisposition为null以禁止浏览器自动打开文件,               //保证点击链接后是下载文件。若不设定,则下载的文件扩展名为               //doc时,浏览器将自动用word打开它。扩展名为pdf时,               //浏览器将用acrobat打开。        su.setContentDisposition(null);               // 下载文件        su.downloadFile("/upload/如何赚取我的第一桶金.doc");%>
     注意,执行下载的页面,在Java脚本范围外(即<% ... %>之外),不要包含HTML代码、空格、回车或换行等字符,有的话将不能正确下载。不信的话,可以在上述源码中%><%之间加入一个换行符,再下载一下,保证出错。因为它影响了返回给浏览器的数据流,导致解析出错。 3、如何下载中文文件 jspSmartUpload虽然能下载文件,但对中文支持不足。若下载的文件名中有汉字,则浏览器在提示另存的文件名时,显示的是一堆乱码,很扫人兴。上面的例子就是这样。(这个问题也是众多下载组件所存在的问题,很少有人解决,搜索不到相关资料,可叹!) 为了给jspSmartUpload组件增加下载中文文件的支持,我对该组件进行了研究,发现对返回给浏览器的另存文件名进行UTF-8编码后,浏览器便能正确显示中文名字了。这是一个令人高兴的发现。于是我对jspSmartUpload组件的SmartUpload类做了升级处理,增加了toUtf8String这个方法,改动部分源码如下: 
    public void downloadFile(String s, String s1, String s2, int i)        throws ServletException, IOException, SmartUploadException    {        if(s == null)            throw new IllegalArgumentException("File '" + s +            "' not found (1040).");        if(s.equals(""))            throw new IllegalArgumentException("File '" + s +            "' not found (1040).");        if(!isVirtual(s) && m_denyPhysicalPath)            throw new SecurityException("Physical path is            denied (1035).");        if(isVirtual(s))            s = m_application.getRealPath(s);        java.io.File file = new java.io.File(s);        FileInputStream fileinputstream = new FileInputStream(file);        long l = file.length();        boolean flag = false;        int k = 0;        byte abyte0[] = new byte[i];        if(s1 == null)            m_response.setContentType("application/x-msdownload");        else        if(s1.length() == 0)            m_response.setContentType("application/x-msdownload");        else            m_response.setContentType(s1);        m_response.setContentLength((int)l);        m_contentDisposition = m_contentDisposition != null ?        m_contentDisposition : "attachment;";        if(s2 == null)            m_response.setHeader("Content-Disposition",             m_contentDisposition + " filename=" +             toUtf8String(getFileName(s)));        else        if(s2.length() == 0)            m_response.setHeader("Content-Disposition",             m_contentDisposition);        else            m_response.setHeader("Content-Disposition",             m_contentDisposition + " filename=" + toUtf8String(s2));        while((long)k < l)        {            int j = fileinputstream.read(abyte0, 0, i);            k += j;            m_response.getOutputStream().write(abyte0, 0, j);        }        fileinputstream.close();    }     /**     * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.     * 纵横软件制作中心雨亦奇2003.08.01     * @param s 原文件名     * @return 重新编码后的文件名     */    public static String toUtf8String(String s) {        StringBuffer sb = new StringBuffer();        for (int i=0;i<s.length();i++) {            char c = s.charAt(i);            if (c >= 0 && c <= 255) {               sb.append(c);            } else {               byte[] b;               try {                   b = Character.toString(c).getBytes("utf-8");               } catch (Exception ex) {                   System.out.println(ex);                   b = new byte[0];               }               for (int j = 0; j < b.length; j++) {                   int k = b[j];                   if (k < 0) k += 256;                   sb.append("%" + Integer.toHexString(k).                   toUpperCase());               }            }        }        return sb.toString();    }
     注意源码中粗体部分,原jspSmartUpload组件对返回的文件未作任何处理,现在做了编码的转换工作,将文件名转换为UTF-8形式的编码形式。UTF-8编码对英文未作任何处理,对中文则需要转换为%XX的形式。toUtf8String方法中,直接利用Java语言提供的编码转换方法获得汉字字符的UTF-8编码,之后将其转换为%XX的形式。 将源码编译后打包成jspSmartUpload.jar,拷贝到Tomcat的shared/lib目录下(可为所有WEB应用程序所共享),然后重启Tomcat服务器就可以正常下载含有中文名字的文件了。另,toUtf8String方法也可用于转换含有中文的超级链接,以保证链接的有效,因为有的WEB服务器不支持中文链接。 小结:jspSmartUpload组件是应用JSP进行B/S程序开发过程中经常使用的上传下载组件,它使用简单,方便。现在我又为其加上了下载中文名字的文件的支持,真个是如虎添翼,必将赢得更多开发者的青睐。
      

  6.   

    我的意思是把这个文件生成到你工程的目录底下,然后通过url不就可以下载了么
      

  7.   

    通过url也可以下载的,你可以生成以后,在成生一个网页里面有那个url,一点也能下载
      

  8.   

    InputStream reader = null;
     ServletOutputStream outputStream = null;

    File file = new File(path);
     reader = new FileInputStream(file); outputStream = response.getOutputStream();
                setResponseBeforeDownload(
                    response, fileName);
                int len = 0; 
                if (outputStream != null) {
                    final byte[] c = new byte[2048];
                    while ((len = reader.read(c)) > 0) {
                        outputStream.write(c, 0, len);
                    }
                }  if (outputStream != null) {
                        outputStream.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
    }
        public static final void setResponseBeforeDownload(
            HttpServletResponse response,
            String filename)
            throws ZZServerException {
            try {
                response.setCharacterEncoding("Shift_JIS");
                response.setContentType("application/x-msbinary");
                response.setHeader(
                    "Content-Disposition",
                    "attachment; filename="
                        + new String(filename.getBytes("Shift_JIS"), "ISO8859_1"));
            } catch (UnsupportedEncodingException e) {
            }
        }
      

  9.   


    <%@ page language="java" import="java.util.*,java.io.*" pageEncoding="gbk"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        
        
        <title>My JSP '1.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
        <%
        File   file   =   new   File("c:\\test.xls");   
        FileInputStream inStream = new FileInputStream(file);  
        String to =  request.getRealPath("")+"/test.xls";
        String path = request.getContextPath();
     FileOutputStream outStream = new FileOutputStream(to);
        int bytesRead = 0;
    byte[] b = new byte[8192];
    while ((bytesRead = inStream.read(b, 0, 8192)) != -1) {
    outStream.write(b, 0, bytesRead);
    }
    inStream.close();
    outStream.close();
        response.sendRedirect(path+"/test.xls");
        %>
        
      </body>
    </html>注意要在web.xml里加 
      <mime-mapping>
        <extension>doc</extension>
        <mime-type>application/msword</mime-type>
      </mime-mapping>
      <mime-mapping>
        <extension>xls</extension>
        <mime-type>application/msexcel</mime-type>
      </mime-mapping>
      

  10.   

    luyang1016(闭月羞花猫) 好像不行啊,你的QQ 号是,我加你,
      

  11.   

    iider() 你的方法我试过,问题还是那样
      

  12.   

    不太会applet
    我这个是,一点击down.jsp页面就出现了大面积的乱码,后台还没有错误
      

  13.   

    都和你说了,用组件方法下载就行了,你直接用链接点击下载当然会出现这种问题
     su.downloadFile("/upload/ddd.doc");
      

  14.   

    File   f   =   new   File("c:\\测试.xls");   
      FileInputStream   fin   =   new   FileInputStream(f);   
      
      OutputStream   output   =   response.getOutputStream();   
      byte[]   buf   =   new   byte[1024];   
      int   r   =   0;  
      response.setContentType("application/vnd.ms-excel;charset=GB2312");   
      response.setHeader("Content-Disposition",   "attachment;   filename=测试.xls");  
      while((r   =   fin.read(buf,   0,   buf.length))!=   -1)   {   
                output.write(buf,   0,   r);   
      }   
      fin.close();   
      output.close(); 
    LZ你这样写就没有乱玛问题了 而且可以下载的(我已经验证了)