Servlet实现web站点文件下载功能示例
前段时间事情比较多,导致二月份没有记录自己的学习情况。最近接触了servlet,参考韩老师的教程自己写了一个web站点文件下载的小项目,该项目中还加入了简单的反盗链技术。
1、首先创建一个SharedFilesServlet用于返回一个文件分享界面
1 package com.hyman.view; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 /** 12 * Servlet implementation class SharedFilesServlet 13 */ 14 public class SharedFilesServlet extends HttpServlet { 15 private static final long serialVersionUID = 1L; 16 17 /** 18 * @see HttpServlet#HttpServlet() 19 */ 20 public SharedFilesServlet() { 21 super(); 22 // TODO Auto-generated constructor stub 23 } 24 25 /** 26 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 27 */ 28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 29 // TODO Auto-generated method stub 30 response.setContentType("text/html; charset=utf-8"); 31 PrintWriter out = response.getWriter(); 32 out.println("<script type='text/javascript' language='javascript'>" 33 + "function fileDown(obj){" 34 + "var resourceName = '';" 35 + "var buttonId = obj.getAttribute('id');" 36 + "var eleName = buttonId.substring(0,3) + 'File';" 37 + "resourceName = document.getElementsByName(eleName)[0].value;" 38 + "var url = '/SharingSite/DownFileServlet?fileName=' + resourceName;" 39 + "window.location.href=url;" 40 + "}" 41 + "</script>"); 42 out.println("<h1>文件共享网站</h1>"); 43 out.println("mp3资源:<input type='text' name='mp3File' /> <input type='submit' value ='点击下载' id='mp3Down' onclick='fileDown(this)' /><br/>"); 44 out.println("avi资源:<input type='text' name='aviFile' /> <input type='submit' value ='点击下载' id='aviDown' onclick='fileDown(this)' /><br/>"); 45 out.println("jpg资源:<input type='text' name='jpgFile' /> <input type='submit' value ='点击下载' id='jpgDown' onclick='fileDown(this)' /><br/>"); 46 out.println("txt资源:<input type='text' name='txtFile' /> <input type='submit' value ='点击下载' id='txtDown' onclick='fileDown(this)' /><br/>"); 47 } 48 49 /** 50 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 51 */ 52 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 53 // TODO Auto-generated method stub 54 this.doGet(request, response); 55 } 56 57 }
2、然后创建一个控制器,来判断是否盗链,以及处理文件下载逻辑:
1 package com.hyman.controller; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class DownFileServlet 15 */ 16 public class DownFileServlet extends HttpServlet { 17 private static final long serialVersionUID = 1L; 18 19 /** 20 * @see HttpServlet#HttpServlet() 21 */ 22 public DownFileServlet() { 23 super(); 24 // TODO Auto-generated constructor stub 25 } 26 27 /** 28 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 29 */ 30 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 // TODO Auto-generated method stub 32 response.setContentType("text/html; charset=utf-8"); 33 String referer = request.getHeader("Referer"); 34 if (referer == null || !referer.startsWith("http://localhost:8080/SharingSite/")) { 35 response.sendRedirect("/SharingSite/AntiPirateLink"); 36 } else { 37 String fileName = request.getParameter("fileName"); 38 response.setHeader("Content-Disposition", "attachment; filename="+fileName); 39 String path = this.getServletContext().getRealPath("/resources/"+fileName); 40 FileInputStream fis = null; 41 OutputStream os = null; 42 try { 43 fis = new FileInputStream(new File(path)); 44 byte buff[] = new byte[1024]; 45 int len = 0; 46 os = response.getOutputStream(); 47 while ((len = fis.read(buff)) > 0) { 48 os.write(buff, 0, len); 49 } 50 } catch (Exception e) { 51 e.printStackTrace(); 52 throw new RuntimeException(); 53 } finally { 54 if (os != null) os.close(); 55 if (fis != null) fis.close(); 56 } 57 } 58 59 } 60 61 /** 62 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 63 */ 64 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 65 // TODO Auto-generated method stub 66 this.doGet(request, response); 67 } 68 69 }
3、创建一个AntiPirateLink返回盗链提醒界面,并在10秒后自动刷新跳转到SharedFilesServlet
1 package com.hyman.view; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 /** 12 * Servlet implementation class AntiPirateLink 13 */ 14 public class AntiPirateLink extends HttpServlet { 15 private static final long serialVersionUID = 1L; 16 17 /** 18 * @see HttpServlet#HttpServlet() 19 */ 20 public AntiPirateLink() { 21 super(); 22 // TODO Auto-generated constructor stub 23 } 24 25 /** 26 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 27 */ 28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 29 // TODO Auto-generated method stub 30 response.setContentType("text/html; charset=utf-8"); 31 PrintWriter out = response.getWriter(); 32 out.println("<script type='text/javascript' language='javascript'>" 33 + "var i = 10;" 34 + "function showTime(){" 35 + "if(i > 0) {document.getElementById('time').innerHTML = '请不要盗链下载... ' + i +' 秒后自动跳转到下载首页...';" 36 + "i--;}" 37 + "}" 38 + "setInterval('showTime()',1000);" 39 + "</script>"); 40 out.println("<span id='time'></span>"); 41 response.setHeader("Refresh", "10; url=/SharingSite/SharedFilesServlet"); 42 } 43 44 /** 45 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 46 */ 47 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 48 // TODO Auto-generated method stub 49 this.doGet(request, response); 50 } 51 52 }
【分析】文件下载部分实现步骤:
1、response.setHeader("Content-Disposition", "attachment; filename="+fileName);在http回复消息头中的Content-Disposition中指明下文件的文件名;
2、调用this.getServletContext().getRealPath("/resources/"+fileName);函数获取到文件的全路径;
3、使用文件流FileInputStream将文件读入到服务器内存,重要要用到缓存处理,然后再调用response的getOutputStream()方法获得向客户端写文件的输出文件流;