1.工具類(lèi)downloadUtils.java的核心部分
- //服務(wù)器使客戶(hù)端可以從遠程url下載文件
- public void download(String fileUrl, HttpServletResponse response) throws ServletException, IOException {
- String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") +1, fileUrl.length());// 文件名稱(chēng)
- URL url = new URL(fileUrl);
- URLConnection conn = url.openConnection();
- int filesize = conn.getContentLength(); // 取數據長(cháng)度
- BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
- // 清空response
- response.reset();
- // 文件名稱(chēng)轉換編碼格式為utf-8,保證不出現亂碼,這個(gè)文件名稱(chēng)用于瀏覽器的下載框中自動(dòng)顯示的文件名
- 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");
- // 從輸入流中讀入字節流,然后寫(xiě)到文件中
- byte[] buffer = new byte[1024];
- int nRead;
- while ((nRead = bis.read(buffer, 0, 1024)) > 0) { // bis為網(wǎng)絡(luò )輸入流
- 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開(kāi)始。。。");
- //1.服務(wù)器使客戶(hù)端從網(wǎng)絡(luò )上下載文件
- String url = "http://apps.bdimg.com/libs/accounting.js/0.3.2/accounting.min.js";
- fileDownload fd = new fileDownload();
- // fd.download(url, response);
- //2.服務(wù)器從本地拿文件給和客戶(hù)端
- 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方法中寫(xiě)了兩種測試方法:
1.一種是瀏覽器從其他網(wǎng)站下資源,本地的服務(wù)器只是提供這種鏈接下載的服務(wù),使客戶(hù)端可以不需要能訪(fǎng)問(wèn)這個(gè)url即可下載此資源,服務(wù)器代為傳輸下載,即服務(wù)器提供鏈接和傳輸中介服務(wù)。使用http協(xié)議。
2.另一種是瀏覽器從服務(wù)器的本地設備中獲取,即服務(wù)器從自己硬盤(pán)中拿出文件給客戶(hù)端。使用本地文本傳輸協(xié)議file協(xié)議。這種更常見(jiàn)。
3.這兩種服務(wù)都需要使用協(xié)議不管是http協(xié)議還是本地文本傳輸協(xié)議file協(xié)議。
4.doGet中這個(gè)兩種方法必須有分開(kāi)測試,即測試一個(gè)注釋一個(gè),不然一個(gè)測試I/O流關(guān)閉后會(huì )導致另一個(gè)報錯,你也可以new兩次fileDownload。我是為了測試效果,才測一個(gè)注掉一個(gè)。
為了讓你的servlet運行起來(lái),我給出web.xml
3.web.xml(需要手動(dòng)在WEB-INF目錄下手動(dòng)新建目錄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>
在啟動(dòng)servlet后,需要測試。4.用瀏覽器打開(kāi)點(diǎn)擊鏈接測試的HTML頁(yè)面testServletDownload.html:
- <!doctype html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>測試客戶(hù)端下載文件頁(yè)面</title>
- </head>
- <body>
- <a href="http://localhost:8080/demoProj/webxmlServlet">點(diǎn)我下載文件</a>
- </body>
- </html>
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。