1. 程式人生 > >瀏覽器從伺服器下載檔案的Servlet例項

瀏覽器從伺服器下載檔案的Servlet例項

測試兩種下載:瀏覽器通過伺服器下載其他網站檔案(http協議);瀏覽器下載伺服器本地硬盤裡的檔案(file協議)

1.工具類downloadUtils.java的核心部分

//伺服器使客戶端可以從遠端url下載檔案
	public void download(String fileUrl, HttpServletResponse response) throws ServletException, IOException {
		String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") +1, fileUrl.length());// 檔名稱
		URL url = new URL(fileUrl);
		URLConnection conn = url.openConnection();
		int filesize = conn.getContentLength(); // 取資料長度
		BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
		// 清空response
		response.reset();
		// 檔名稱轉換編碼格式為utf-8,保證不出現亂碼,這個檔名稱用於瀏覽器的下載框中自動顯示的檔名
		response.addHeader("Content-Disposition",
		        "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
		response.addHeader("Content-Length", "" + filesize);
		BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/octet-stream");
		// 從輸入流中讀入位元組流,然後寫到檔案中
		byte[] buffer = new byte[1024];
		int nRead;
		while ((nRead = bis.read(buffer, 0, 1024)) > 0) { // bis為網路輸入流
		os.write(buffer, 0, nRead);
		}
		bis.close();
		os.flush();
		os.close();
		}

2.Servlet核心部分webxmlServlet.java(只需看doGet方法即可,其他的可不看):
package test;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class webxmlServlet
 */
public class webxmlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public webxmlServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init()
    {
        String userName;
		String userName1;
		String path;
		try {
			ServletConfig config = getServletConfig();
			userName = config.getInitParameter("username");
			userName1 = this.getInitParameter("username");
			path = config.getInitParameter("path");
			System.out.println("初始化獲得的userName:"+userName);//初始化獲得的userName:admin
			System.out.println("初始化獲得的userName1:"+userName1);//初始化獲得的userName1:admin
			System.out.println("初始化獲得的path:"+path);//初始化獲得的path:null
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		System.out.println("webxmlServlet的doGet開始。。。");
		//1.伺服器使客戶端從網路上下載檔案
		String url  = "http://apps.bdimg.com/libs/accounting.js/0.3.2/accounting.min.js";
		fileDownload fd = new fileDownload();
//		fd.download(url, response);
		//2.伺服器從本地拿檔案給和客戶端
		String localUrl = "file:///D:/test/test1.txt";
		fd.download(localUrl, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

注意:doGet方法中寫了兩種測試方法:

1.一種是瀏覽器從其他網站下資源,本地的伺服器只是提供這種連結下載的服務,使客戶端可以不需要能訪問這個url即可下載此資源,伺服器代為傳輸下載,即伺服器提供連結和傳輸中介服務。使用http協議。

2.另一種是瀏覽器從伺服器的本地裝置中獲取,即伺服器從自己硬碟中拿出檔案給客戶端。使用本地文字傳輸協議file協議。這種更常見。

3.這兩種服務都需要使用協議不管是http協議還是本地文字傳輸協議file協議。

4.doGet中這個兩種方法必須有分開測試,即測試一個註釋一個,不然一個測試I/O流關閉後會導致另一個報錯,你也可以new兩次fileDownload。我是為了測試效果,才測一個注掉一個。

為了讓你的servlet執行起來,我給出web.xml
3.web.xml(需要手動在WEB-INF目錄下手動新建目錄classes/log4j.properties)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>path</param-name>
    <param-value>/WEB-INF/config.properties</param-value>
  </context-param>
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.properties</param-value>
  </context-param>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>CheckAccount</servlet-name>
    <servlet-class>com.ht.servlet.CheckAccount</servlet-class>
    <init-param>
      <param-name>username</param-name>
      <param-value>admin</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>CheckAccount</servlet-name>
    <url-pattern>/CheckAccount</url-pattern>
  </servlet-mapping>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>webxmlServlet</servlet-name>
    <servlet-class>test.webxmlServlet</servlet-class>
    <init-param>
      <param-name>username</param-name>
      <param-value>admin</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>webxmlServlet</servlet-name>
    <url-pattern>/webxmlServlet</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>40</session-timeout>
  </session-config>
  <error-page>
    <error-code>404</error-code>
    <location>/login.jsp</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/login.jsp</location>
  </error-page>
  
 <!--  <filter>
  <filter-name>Encoding</filter-name>
  <filter-class>ghjf.test.filter.SetCharacterEncodingFilter</filter-class>
  <init-param>
     <param-name>encoding</param-name>
     <param-value>UTF-8</param-value>
  </init-param>
</filter>

<filter-mapping>
   <filter-name>Encoding</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping> -->
</web-app>
在啟動servlet後,需要測試。

4.用瀏覽器開啟點選連結測試的HTML頁面testServletDownload.html:

<!doctype html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>測試客戶端下載檔案頁面</title>
 </head>
 <body>
<a href="http://localhost:8080/demoProj/webxmlServlet">點我下載檔案</a>
 </body>
</html>