码迷,mamicode.com
首页 > 其他好文 > 详细

关于使用servlet下载中文名称的文件

时间:2014-10-14 05:09:08      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:下载中文   method   request   用户   status   

在jsp页面用servlet使用js调用:

var win=window.open("DownloadYhscServlet",‘用户手册下载‘, ‘height=‘+iHeight+‘, width=‘+iWidth+‘,top=‘+iTop+‘,left=‘+iLeft+‘,status=no,scrollbars=no, resizable=no‘);

在servlet中实现下载的方法:

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try
  {
   String downFilename="用户手册.doc";
   //获取项目当前路径
   String filepath=this.getServletConfig().getServletContext().getRealPath("/");
   response.setContentType("text/plain");
   response.setContentType("application/vnd.ms-excel;charset=UTF-8");
   response.setHeader("Location",downFilename);
   //处理中文
   downFilename = URLEncoder.encode(downFilename, "UTF-8");
   response.setHeader("Content-Disposition", "attachment; filename=" + downFilename);
   OutputStream outputStream = response.getOutputStream();
   InputStream inputStream = new FileInputStream(filepath+"/upload/用户手册.doc");
   byte[] buffer = new byte[1024];
   int i = -1;
   while ((i = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, i);
      }
   outputStream.flush();
   outputStream.close();
  }catch(FileNotFoundException e1)
  {
   System.out.println("没有找到您要的文件");
  }
  catch(Exception e)
  {
   System.out.println("系统错误,请及时与管理员联系");
  }
}

开始的时候用过jspsmartupload组件进行下载,但是发现这个jar虽然好用,但是对中文名称处理不好,会产生乱码,所以,只能使用文件流来进行文件的下载,在文件流下载中,也要使用

downFilename = URLEncoder.encode(downFilename, "UTF-8");

来进行中文的处理,可以实现中文名称文件的下载。

本文出自 “butcher36” 博客,请务必保留此出处http://butcher36.blog.51cto.com/9315484/1563438

关于使用servlet下载中文名称的文件

标签:下载中文   method   request   用户   status   

原文地址:http://butcher36.blog.51cto.com/9315484/1563438

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!