在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");
来进行中文的处理,可以实现中文名称文件的下载。
时间: 2024-10-31 11:56:35