文件下载:
- 被下载的文件必须放到WEB-INF下面,不能让用户直接访问到。然后通过servlet下载就行。下载很简单,如下
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("path"); //处理中文乱码问题 fileName = new String(fileName.getBytes("ISO-8859-1"),"utf-8"); //得到文件保存路径 String filePath = this.getServletContext().getRealPath("/WEB-INF/download")+"\\"+fileName; File file = new File(filePath); //如果文件不存在 if(!file.exists()){ System.out.println("文件不存在"); return; } if(request.getHeader("User-Agent").contains("MSIE")){//是IE浏览器 //这样处理 fileName = new String(fileName.getBytes("gbk"),"ISO-8859-1"); }else{ //其他浏览器这样处理 fileName = new String(fileName.getBytes("utf-8"),"ISO-8859-1"); } //设置响应头信息,并在浏览器弹出框中设置显示的文件名 response.addHeader("content-disposition", "attachment;filename="+fileName); //使用commons包类实现下载 IOUtils.copy(new FileInputStream(file), response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }