java web文件下載功能實現 (轉)

http://blog.csdn.net/longshengguoji/article/details/39433307html

需求:實現一個具備文件下載功能的網頁,主要下載壓縮包和圖片java

兩種實現方法:瀏覽器

    一:經過超連接實現下載

在HTML網頁中,經過超連接連接到要下載的文件的地址
[html] view plain copy
 
print?
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Insert title here</title>  
  6. </head>  
  7. <body>  
  8. <h1>經過連接下載文件</h1>  
  9. <href="/day06/download/cors.zip">壓縮包</a>  
  10. <href="/day06/download/1.png">圖片</a>  
  11. </body>  
  12. </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>
</body>
</html>

其中day06/download是文檔路徑,本實例的程序結構以下:
程序運行後,能夠經過單擊須要下載文檔實現下載
可是這裏會出現一個問題,就是單擊下載壓縮包的時候會彈出下載頁面,可是下載圖片的時候瀏覽器就直接打開了圖片,沒有下載。
    這是由於經過超連接下載文件時,若是瀏覽器能夠識別該文件格式,瀏覽器就會直接打開。只有瀏覽器不能識別該文件格式的時候,纔會實現下載。所以利用第二種方法實現下載功能。

    二:經過Servlet程序實現下載

    經過Servlet下載文件的原理是經過servlet讀取目標程序,將資源返回客戶端。
[html] view plain copy
 
print?
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Insert title here</title>  
  6. </head>  
  7. <body>  
  8. <h1>經過連接下載文件</h1>  
  9. <href="/day06/download/cors.zip">壓縮包</a>  
  10. <href="/day06/download/1.png">圖片</a>  
  11. <h1>經過servlet程序下載文件</h1>  
  12. <href="/day06/ServletDownload?filename=cors.zip">壓縮包</a>  
  13. <href="/day06/ServletDownload?filename=1.png">圖片</a>  
  14. </body>  
  15. </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>

其中,/day06/ServletDownload 是servlet程序的映射路徑
而後新建一個servlet,名稱爲ServletDownload,URL映射爲/ServletDownload
添加代碼以下:
[java] view plain copy
 
print?
  1. package com.lsgjzhuwei.servlet.response;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.annotation.WebServlet;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. /** 
  16.  * Servlet implementation class ServletDownload 
  17.  */  
  18. @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })  
  19. public class ServletDownload extends HttpServlet {  
  20.     private static final long serialVersionUID = 1L;  
  21.          
  22.     /** 
  23.      * @see HttpServlet#HttpServlet() 
  24.      */  
  25.     public ServletDownload() {  
  26.         super();  
  27.         // TODO Auto-generated constructor stub  
  28.     }  
  29.   
  30.     /** 
  31.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  32.      */  
  33.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  34.         // TODO Auto-generated method stub  
  35.           
  36.         //得到請求文件名  
  37.         String filename = request.getParameter("filename");  
  38.         System.out.println(filename);  
  39.           
  40.         //設置文件MIME類型  
  41.         response.setContentType(getServletContext().getMimeType(filename));  
  42.         //設置Content-Disposition  
  43.         response.setHeader("Content-Disposition", "attachment;filename="+filename);  
  44.         //讀取目標文件,經過response將目標文件寫到客戶端  
  45.         //獲取目標文件的絕對路徑  
  46.         String fullFileName = getServletContext().getRealPath("/download/" + filename);  
  47.         //System.out.println(fullFileName);  
  48.         //讀取文件  
  49.         InputStream in = new FileInputStream(fullFileName);  
  50.         OutputStream out = response.getOutputStream();  
  51.           
  52.         //寫文件  
  53.         int b;  
  54.         while((b=in.read())!= -1)  
  55.         {  
  56.             out.write(b);  
  57.         }  
  58.           
  59.         in.close();  
  60.         out.close();  
  61.     }  
  62.   
  63.     /** 
  64.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  65.      */  
  66.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  67.         // TODO Auto-generated method stub  
  68.     }  
  69.   
  70. }  
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
	}

}

重啓tomcat服務器,便可實現對壓縮包和對圖片的下載。
相關文章
相關標籤/搜索