JSP 可以與 HTML form 標(biāo)簽一起使用,來允許用戶上傳文件到服務(wù)器。上傳的文件可以是文本文件或圖像文件或任何文檔。
本章節(jié)我們使用 Servlet 來處理文件上傳,使用到的文件有:
upload.jsp : 文件上傳表單。
message.jsp : 上傳成功后跳轉(zhuǎn)頁面。
UploadServlet.java : 上傳處理 Servlet。
需要引入的 jar 文件:commons-fileupload-1.3.2、commons-io-2.5.jar。
結(jié)構(gòu)圖如下所示:

接下來我們詳細介紹。
下面的 HTML 代碼創(chuàng)建了一個文件上傳表單。以下幾點需要注意:
表單 method 屬性應(yīng)該設(shè)置為 POST 方法,不能使用 GET 方法。
表單 enctype 屬性應(yīng)該設(shè)置為 multipart/form-data.
表單 action 屬性應(yīng)該設(shè)置為在后端服務(wù)器上處理文件上傳的 Servlet 文件。下面的示例使用了 UploadServlet Servlet 來上傳文件。
上傳單個文件,您應(yīng)該使用單個帶有屬性 type="file" 的 <input .../> 標(biāo)簽。為了允許多個文件上傳,請包含多個 name 屬性值不同的 input 標(biāo)簽。輸入標(biāo)簽具有不同的名稱屬性的值。瀏覽器會為每個 input 標(biāo)簽關(guān)聯(lián)一個瀏覽按鈕。
upload.jsp 文件代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件上傳示例 - 菜鳥教程</title> </head> <body> <h1>文件上傳示例 - 菜鳥教程</h1> <form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data"> 選擇一個文件: <input type="file" name="uploadFile" /> <br/><br/> <input type="submit" value="上傳" /> </form> </body> </html>
以下是 UploadServlet 的源代碼,同于處理文件上傳,在這之前我們先確保依賴包已經(jīng)引入到項目的 WEB-INF/lib 目錄下:
下面的示例依賴于 FileUpload,所以一定要確保在您的 classpath 中有最新版本的 commons-fileupload.x.x.jar 文件??梢詮?http://commons.apache.org/proper/commons-fileupload/ 下載。
FileUpload 依賴于 Commons IO,所以一定要確保在您的 classpath 中有最新版本的 commons-io-x.x.jar 文件??梢詮?http://commons.apache.org/proper/commons-io/ 下載。
你可以直接下載本站提供的兩個依賴包:
UploadServlet 的源代碼 如下所示:
package com.nhooo.test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
// 如果不配置 web.xml ,可以使用下面的代碼
// @WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上傳文件存儲目錄
private static final String UPLOAD_DIRECTORY = "upload";
// 上傳配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* 上傳數(shù)據(jù)及保存文件
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 檢測是否為多媒體上傳
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上傳參數(shù)
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設(shè)置內(nèi)存臨界值 - 超過后將產(chǎn)生臨時文件并存儲于臨時目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設(shè)置臨時存儲目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設(shè)置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設(shè)置最大請求值 (包含文件和表單數(shù)據(jù))
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文處理
upload.setHeaderEncoding("UTF-8");
// 構(gòu)造臨時路徑來存儲上傳的文件
// 這個路徑相對當(dāng)前應(yīng)用的目錄
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
// 如果目錄不存在則創(chuàng)建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析請求的內(nèi)容提取文件數(shù)據(jù)
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單數(shù)據(jù)
for (FileItem item : formItems) {
// 處理不在表單中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制臺輸出文件的上傳路徑
System.out.println(filePath);
// 保存文件到硬盤
item.write(storeFile);
request.setAttribute("message",
"文件上傳成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"錯誤信息: " + ex.getMessage());
}
// 跳轉(zhuǎn)到 message.jsp
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
}message.jsp 文件代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上傳結(jié)果</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>編譯上面的 Servlet UploadServlet,并在 web.xml 文件中創(chuàng)建所需的條目,如下所示:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.nhooo.test.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/TomcatTest/UploadServlet</url-pattern> </servlet-mapping> </web-app>
現(xiàn)在嘗試使用您在上面創(chuàng)建的 HTML 表單來上傳文件。當(dāng)您在瀏覽器中訪問:http://localhost:8080/TomcatTest/upload.jsp ,演示如下所示:
