1.利用响应输出流进行文件的下载:response.getOutputStream();
关键技术:
本实例主要设置响应头的信息和输出流进行实现:在servlet中
设置响应头:response.setContextType("application/x-msdownFile")
2.设置响应头:response.setHeader("content-Disposition","attachment; filename=" +java.net.URLEncoder.encode(filename,"utf-8"));
下面使用响应流 在Servlet:
1 System.out.println("dounload servlet"); 2 String path=request.getParameter("path"); 3 // JSP 页面上超链接方式,不是同一个request请求,Session att=null 4 String att=(String) request.getAttribute("path1"); 5 6 7 InputStream in=getServletContext().getResourceAsStream("/WEB-INF/files/"+path); 8 9 if(in ==null) 10 { 11 request.getRequestDispatcher("/APP/404.jsp").forward(request, response);; 12 } 13 //以响应流方式输出对象 14 response.setCharacterEncoding("UTF-8"); 15 response.setContentType("application/x-msdownload"); 16 String fileName=path; 17 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 18 OutputStream out=response.getOutputStream(); 19 byte[] buffer=new byte[1024]; 20 21 int len=0; 22 while((len=in.read(buffer))!=-1) 23 { 24 out.write(buffer,0,len); 25 } 26 in.close();
注意:将文件名转换成UTF-8,使用流的方式 注意编码的方式 设置成一致,造成文件名出现乱码,JSP页面的编码方式和response.setCharacterEncoding("utf-8")
2.防止网站文件盗链接下载:
关键技术:应用request对象中getHeader()的方法,获取getHeader中referer字段,该值记录了当前请求的上一次访问的地址,
1 String from=request.getHeader("Referer"); 2 System.out.println(from); 3 if(from==null || (from.indexOf("localhost:8080/day_04")<0)) 4 request.getRequestDispatcher("/APP/404.jsp").forward(request, response);; 5 6 System.out.println("dounload servlet"); 7 String path=request.getParameter("path"); 8 // JSP 页面上超链接方式,不是同一个request请求,Session att=null 9 10 11 String att=(String) request.getAttribute("path1"); 12 13 14 InputStream in=getServletContext().getResourceAsStream("/WEB-INF/files/"+path); 15 16 if(in ==null) 17 { 18 request.getRequestDispatcher("/APP/404.jsp").forward(request, response);; 19 } 20 //以响应流方式输出对象 21 response.setCharacterEncoding("UTF-8"); 22 response.setContentType("application/x-msdownload"); 23 String fileName=path; 24 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 25 OutputStream out=response.getOutputStream(); 26 byte[] buffer=new byte[1024]; 27 28 int len=0; 29 while((len=in.read(buffer))!=-1) 30 { 31 out.write(buffer,0,len); 32 } 33 in.close();