我做了一个java文件下载不能下中文
下面我把代码给大家看看帮我解决一下
我觉得问题有2个
1.用迅雷测试下载的时候下载所显示的文件名找不到只显示我的servlet名称必须自己写名称菜行
2.就是乱码工程报出异常就是文件名后面是乱码的异常就是找不到文件
String name=new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");
//得到文件的路径也是tomcat服务器上面的路径文件上传都上传到了tomcat下面
String path=request.getSession().getServletContext().getRealPath("/upload/");
//要下载的文件名称
File file=new File(path+"/"+name);
//System.out.println(file.getName());
//设置下载文件的类型为任意类型
response.setContentType("application/x-msdownload");
//添加下载文件的头信息。此信息在下载时会在下载面板上显示,比如:
//迅雷下载显示的文件名称,就是此处filiname
response.addHeader("Content-Disposition","attachment;filename="+file.getName());
//添加文件的大小信息
response.setContentLength((int) file.length());
//获得输出网络流
ServletOutputStream sos=response.getOutputStream();
FileInputStream fis=new FileInputStream(file);
byte[] buffer=new byte[1024];
int i=0;
while((i=fis.read(buffer))!=-1){
sos.write(buffer,0,i);
sos.flush();
}
sos.close();
fis.close();

}希望大虾们帮我解决下

解决方案 »

  1.   

    下载用smartupload多好 还用如此麻烦么
      

  2.   

    用smartupload吧,多简单!代码:
    在第一个页面:<a href="do_download.jsp">点击下载</a> 
    第二个页面,处理下载页面:
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@page import="com.jspsmart.upload.SmartUpload"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
        
        <title>My JSP 'do_download.jsp' starting page</title>
        
      </head>
      
      <body>
      <%
      SmartUpload smartUpload = new SmartUpload();
      smartUpload.initialize(pageContext);
      smartUpload.setContentDisposition(null);     //不让其自动显示
      smartUpload.downloadFile("upload/1.gif");
     
       %>
      </body>
    </html>
      

  3.   

    我还有个问题想问问大家就是我做下载吧 
    我用迅雷测试的时候不能显示正常下载文件名称
    缺显示DownloadServlet这个是我的那个java类 
    缺显示这个我不知道怎么修改啊 最上面是我的代码想大家帮我下~~!
      

  4.   

    小夜刀.RMVB
    С???.RMVB
    2011-11-30 8:38:49 org.apache.catalina.core.StandardWrapperValve invoke
    严重: Servlet.service() for servlet DownloadServlet threw exception
    java.io.FileNotFoundException: D:\Program Files\Tomcat-6.0.24\webapps\java1113servlet\upload\С???.RMVB (系统找不到指定的文件。)
    有时候就出现这个问题
      

  5.   

    response.addHeader("Content-Disposition","attachment;filename="+file.getName());我记得这里的文件名要用Urlencoding
      

  6.   

    response.addHeader("Content-Disposition","attachment;filename="+file.getName());我记得这里的文件名要用Urlencoding
    你说的是把filename该为urlencoding不行啊
    变成了我的java类名了DownloadServlet
      

  7.   

    String name=new String(request.getParameter("name").getBytes(),“ISO8859-1”);
      

  8.   

    response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
      

  9.   

    直接把我做过的例子贴出来给你吧!
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLEncoder;import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;public class FileDownServlet extends HttpServlet {
        private static final String CONTENT_TYPE = "application/x-download; charset=UTF-8";    //Initialize global variables
        public void init() throws ServletException {
        }    //Process the HTTP Get request
        public void doGet(HttpServletRequest req, HttpServletResponse res) throws
                ServletException, IOException {     // 服务器相对路径
            String path = req.getParameter("path").replace("/", "\\");
            // 服务器绝对路径
            path = getServletContext().getRealPath("/") + path;        // 检查文件是否存在
            File obj = new File(path);
            if (!obj.exists()) {
              res.setContentType("text/html;charset=UTF-8");
              res.getWriter().print("指定文件不存在!");
              return;
            }        // 读取文件名:用于设置客户端保存时指定默认文件名
            int index = path.lastIndexOf("\\"); // 前提:传入的path字符串以“\”表示目录分隔符
            String fileName = path.substring(index + 1);
     
            // 写流文件到前端浏览器
            ServletOutputStream out = res.getOutputStream();
            res.setContentType("application/x-download");//设置为下载application/x-download
            //res.setHeader("Content-disposition", "attachment;filename=" + fileName);
            res.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
              bis = new BufferedInputStream(new FileInputStream(path));
              bos = new BufferedOutputStream(out);
              byte[] buff = new byte[2048];
              int bytesRead;
              while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
              }
            } catch (IOException e) {
              throw e;
            } finally {
              if (bis != null)
                bis.close();
              if (bos != null)
                bos.close();
            }
          }    //Process the HTTP Post request
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws
                ServletException, IOException {
            doGet(request, response);
        }    //Clean up resources
        public void destroy() {
        }
    }
      

  10.   

    response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
    还是不行啊
      

  11.   

    response.addHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("iso8859_1"), "UTF-8");
      

  12.   

    文件名称--------->????.png
    2011-12-1 13:09:19 org.apache.catalina.core.StandardWrapperValve invoke
    严重: Servlet.service() for servlet DownloadServlet threw exception
    java.io.FileNotFoundException: D:\Java软件\Tomcat-6.0.24\webapps\java1113servlet\upload\????.png (系统找不到指定的文件。)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at com.softeem.java1113.servlet.DownloadServlet.doPost(DownloadServlet.java:53)
    at com.softeem.java1113.servlet.DownloadServlet.doGet(DownloadServlet.java:28)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.softeem.java1113.filter.LoginFilter.doFilter(LoginFilter.java:35)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.softeem.java1113.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    还是这个问题
      

  13.   

    上面是我用迅雷测试就出现了这个问题
    用360浏览器测试可以得到中文
    我的头文件是这样写的
    response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
    用下面的还是得到乱码
    response.addHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("iso8859_1"), "UTF-8");
      

  14.   

    我用迅雷测试的就出现上面这个异常
    我用360浏览器测试很好
    response.addHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("iso8859_1"), "UTF-8");这个得到的还是乱吗
    response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));这个可以得到用360浏览器得到中文
      

  15.   

    String name=new String(request.getParameter("name").getBytes("iso-8859-1"),"utf-8");
    是这段代码有问题,导致找不到文件,跟上面这有什么关系
    name是从哪传过来的
      

  16.   

    给你个工具类:public class Utils {
        /**
         * 把字符串转换成utf-8格式(Excel导出时,文件名调用)
         * 
         * @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) {
        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();
        }    /*
         * 将字符串第一个字母大写
         */
        public static String firstCharToUpperCase(String s) {
    return s == null || s.equals("") ? s : s.substring(0, 1).toUpperCase()
    + s.substring(1);
        }
    }后台调用:String fileName = "数据转换表信息导出.xls";
    if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
        fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
    } else if (request.getHeader("User-Agent").toUpperCase()
    .indexOf("MSIE") > 0) {
        fileName = URLEncoder.encode(fileName, "UTF-8"); // IE浏览器
    } else {
        fileName = Utils.toUtf8String(fileName);
    }
    response.setHeader("Content-Disposition", "attachment;filename="
    + fileName);
    return new ModelAndView("/scanQuery/report", modelMap);