您的位置:首页 > 编程语言 > Java开发

java 下载文件,中文文件名称乱码的问题

2013-01-17 17:10 549 查看
/**

  * 下载文件 处理下载中心的数据包

  *

  * @author wangrr

  */

 protected void DownLoadFile(HttpServletResponse response ,HttpServletRequest request, String Path)

           throws IOException

 {

  String filepath= Path.substring(0,Path.lastIndexOf("/")+1);

  String filename = Path.substring(Path.lastIndexOf("/")+1);

  //解决中文文件名乱码问题(火狐,ie,谷歌都兼容)

  String fileName = java.net.URLEncoder.encode(filename, "UTF-8");

        if (fileName.length() > 150) {

            String guessCharset ="gb2312"; /*根据request的locale 得出可能的编码,中文操作系统通常是gb2312*/

            fileName = new String(filename.getBytes(guessCharset), "ISO8859-1"); 

        }

        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

       

  

  response.reset();

  response.setContentType("application/octet-stream");

  response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

  response.setHeader("Connection", "close");

  ServletOutputStream sos = response.getOutputStream();

  FileInputStream fis = null;

  File d = new File(filepath);

  if (d.exists())

  {

  fis = new FileInputStream(filepath+filename);//

  byte b[] = new byte[1000];

  int j;

  while ((j = fis.read(b)) != -1)

  {

  try

  {

  sos.write(b, 0, j);

  }

  catch (IOException exp)

  {

  }

  }

  fis.close();

  sos.flush();

  sos.close();

  }

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐