http://blog.csdn.net/longshengguoji/article/details/39433307html
需求:實現一個具備文件下載功能的網頁,主要下載壓縮包和圖片java
兩種實現方法:瀏覽器
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>經過連接下載文件</h1> <a href="/day06/download/cors.zip">壓縮包</a> <a href="/day06/download/1.png">圖片</a> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>經過連接下載文件</h1> <a href="/day06/download/cors.zip">壓縮包</a> <a href="/day06/download/1.png">圖片</a> <h1>經過servlet程序下載文件</h1> <a href="/day06/ServletDownload?filename=cors.zip">壓縮包</a> <a href="/day06/ServletDownload?filename=1.png">圖片</a> </body> </html>
package com.lsgjzhuwei.servlet.response; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletDownload */ @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" }) public class ServletDownload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ServletDownload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //得到請求文件名 String filename = request.getParameter("filename"); System.out.println(filename); //設置文件MIME類型 response.setContentType(getServletContext().getMimeType(filename)); //設置Content-Disposition response.setHeader("Content-Disposition", "attachment;filename="+filename); //讀取目標文件,經過response將目標文件寫到客戶端 //獲取目標文件的絕對路徑 String fullFileName = getServletContext().getRealPath("/download/" + filename); //System.out.println(fullFileName); //讀取文件 InputStream in = new FileInputStream(fullFileName); OutputStream out = response.getOutputStream(); //寫文件 int b; while((b=in.read())!= -1) { out.write(b); } in.close(); out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }