當我們在 HTML 表單中選擇本地文件之後點擊“提交”按鈕則會將文件上傳到服務器中,此時該 HTTP 請求正文的數據類型就是 multipart/form-data 型的。而在 Servlet 技術中,該 HTTP 請求會被 Servlet 容器(如 Tomcat)包裝成 HttpServletRequest 對象,再由端所請求的相應 Servlet 進行處理。
但是,如果此時我們在服務器端編寫的 Servlet 一點點地解析這個 HTTP 請求,分離出其中的文本表單和上傳的文件類型,這未免有點低效。於是,我們可以使用 Apache 開源上傳軟件包 fileupload 來簡化這一過程,直接使用即可。下載地址:http://commons.apache.org/fileupload/
在 fileupload 包中, HTTP 請求中的複雜表單元素都被看做一個 FileItem 對象;FileItem 對象必須由 ServletFileUpload 類中的 parseRequest() 方法解析 HTTP 請求(即被包裝之後的 HttpServletRequest 對象)出來,即分離出具體的文本表單和上傳文件;而 ServletFileUpload 對象的創建需要依賴於 FileItemFactory 工廠將獲得的上傳文件
FileItem 對象保存至服務器硬盤,即 DiskFileItem 對象。
呼…把這個 fileupload 包中的關係講得那麼亂,最好還是自己看下載下來的幫助文檔。不過,推薦一個免費的 Java 反編譯器 JD-GUI ,用它能夠很輕鬆地打開 .jar 文件,除了源代碼中的註釋,其他的一覽無遺,很好用啊。下載地址:http://java.decompiler.free.fr/?q=jdgui
好吧,我們的程序要求:
1、提供一個 HTML 文件,用戶可在相應表單中選擇需要上傳的文件;
2、編寫一個名叫 UploadServlet 的Servlet 文件,主要功能是解析上面 HTML 表單所提交的 HTTP 請求,把普通的文本域和文件域分離開來;
3、UploadServlet 根據 web.xml 配置文件中的初始化參數確定好需要在 Web 服務器存放該文件的目錄,將上傳的文件寫入到該存放目錄中,在我的這裏我把上傳的文件保存到 F:\java\JavaWeb\ch05\uploadFile 目錄中,而 F:\java\JavaWeb\ch05\temp 目錄則用作該 Web 應用的臨時目錄。
程序代碼:
upload.html 文件
- <html>
- <head> <title>Servlet 上傳文件</title></head>
- <body >
- <form name="uploadForm" method="POST"
- enctype="MULTIPART/FORM-DATA"
- action="upload">
-
- User Name:<input type="text" name="username" size="30"/>
- Upload File1:<input type="file" name="file1" size="30"/>
- Upload File2:<input type="file" name="file2" size="30"/>
- <input type="submit" name="submit" value="上傳">
- <input type="reset" name="reset" value="重置">
- </form>
- </body>
- </html>
UploadServlet.java 文件
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.io.*;
- import java.util.*;
- import org.apache.commons.fileupload.*;
- import org.apache.commons.fileupload.servlet.*;
- import org.apache.commons.fileupload.disk.*;
-
-
- public class UploadServlet extends HttpServlet
- {
- private String filePath;
- private String tempPath;
-
-
- public void init(ServletConfig config) throws ServletException
- {
- super.init(config);
-
- filePath = config.getInitParameter("filepath");
- tempPath = config.getInitParameter("temppath");
-
- ServletContext context = getServletContext();
-
- filePath = context.getRealPath(filePath);
- tempPath = context.getRealPath(tempPath);
- System.out.println("文件存放目錄、臨時文件目錄準備完畢 ...");
- }
-
-
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws IOException, ServletException
- {
- res.setContentType("text/plain;charset=gbk");
- PrintWriter pw = res.getWriter();
- try{
- DiskFileItemFactory diskFactory = new DiskFileItemFactory();
-
- diskFactory.setSizeThreshold(4 * 1024);
-
- diskFactory.setRepository(new File(tempPath));
-
- ServletFileUpload upload = new ServletFileUpload(diskFactory);
-
- upload.setSizeMax(4 * 1024 * 1024);
-
- List fileItems = upload.parseRequest(req);
- Iterator iter = fileItems.iterator();
- while(iter.hasNext())
- {
- FileItem item = (FileItem)iter.next();
- if(item.isFormField())
- {
- System.out.println("處理表單內容 ...");
- processFormField(item, pw);
- }else{
- System.out.println("處理上傳的文件 ...");
- processUploadFile(item, pw);
- }
- }
-
- pw.close();
- }catch(Exception e){
- System.out.println("使用 fileupload 包時發生異常 ...");
- e.printStackTrace();
- }
- }
-
-
-
- private void processFormField(FileItem item, PrintWriter pw)
- throws Exception
- {
- String name = item.getFieldName();
- String value = item.getString();
- pw.println(name + " : " + value + "\r\n");
- }
-
-
- private void processUploadFile(FileItem item, PrintWriter pw)
- throws Exception
- {
-
- String filename = item.getName();
- System.out.println("完整的文件名:" + filename);
- int index = filename.lastIndexOf("\\");
- filename = filename.substring(index + 1, filename.length());
-
- long fileSize = item.getSize();
-
- if("".equals(filename) && fileSize == 0)
- {
- System.out.println("文件名爲空 ...");
- return;
- }
-
- File uploadFile = new File(filePath + "/" + filename);
- item.write(uploadFile);
- pw.println(filename + " 文件保存完畢 ...");
- pw.println("文件大小爲 :" + fileSize + "\r\n");
- }
-
-
- public void doGet(HttpServletRequest req, HttpServletResponse res)
- throws IOException, ServletException
- {
- doPost(req, res);
- }
- }
web.xml 文件
- <?xml version="1.0" encoding="gb2312"?>
- <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
- version="2.4">
-
- <servlet>
- <servlet-name>UploadServlet</servlet-name>
- <servlet-class>UploadServlet</servlet-class>
-
- <init-param>
- <param-name>filepath</param-name>
- <param-value>uploadFile</param-value>
- </init-param>
- <init-param>
- <param-name>temppath</param-name>
- <param-value>temp</param-value>
- </init-param>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>UploadServlet</servlet-name>
- <url-pattern>/upload</url-pattern>
- </servlet-mapping>
-
- </web-app>