Servlet的文件上傳
以下內容引用自http://wiki.jikexueyuan.com/project/servlet/file-uploading.html:
Servlet可以與HTML form標簽一起使用允許用戶將文件上傳到服務器。上傳的文件可以是文本文件或圖像文件或任何文檔。
一、創建一個文件上傳表單
下述HTML代碼創建了一個文件上傳表單。以下是需要註意的幾點:
-
表單method屬性應該設置為POST方法且不能使用GET方法。
-
表單enctype屬性應該設置為multipart/form-data。
-
表單action屬性應該設置為Servlet文件,能夠在後端服務器處理文件上傳。下面的例子是使用UploadServlet Servlet來上傳文件的。
- 要上傳單個文件,應該使用單個帶有屬性type=“file”的<input .../>標簽。為了允許多個文件上傳,要包含多個帶有name屬性不同值的輸入標簽。瀏覽器將把一個瀏覽按鈕和每個輸入標簽關聯起來。
<html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /><form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" size="50" /> <br /> <input type="submit" value="Upload File" /> </form> </body> </html>
這將顯示如下所示的結果,允許從本地計算機中選擇一個文件,當用戶點擊“上傳文件”時,表單會和選擇的文件一起提交:
二、編寫後臺Servlet
以下是Servlet UploadServlet,會接受上傳的文件並把它儲存在目錄<Tomcat-installation-directory>/webapps/data
中。使用外部配置,如web.xml中的context-param元素,這個目錄名也可以被添加,如下所示:
<web-app> .... <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:\apache-tomcat-5.5.29\webapps\data </param-value> </context-param> .... </web-app>
以下是UploadServlet的源代碼,可以一次處理多個文件的上傳。在繼續操作之前,請確認下列各項:
-
下述例子依賴於FileUpload,所以一定要確保在classpath中有最新版本的commons-fileupload.x.x.jar 文件。可以從http://commons.apache.org/fileupload/中下載。
-
FileUpload依賴於Commons IO,所以一定要確保在classpath中有最新版本的commons-io-x.x.jar文件。可以從http://commons.apache.org/io/中下載。
-
在測試下面實例時,上傳的文件大小不能大於maxFileSize,否則文件將無法上傳。
- 請確保已經提前創建好目錄c:\temp and c:\apache-tomcat-5.5.29\webapps\data。
POM項目可以添加如下依賴:
<!-- commons-fileupload --> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <!-- commons-io --> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
編寫Servlet:
//Import required java libraries import java.io.*; import java.util.*; import javax.servlet.ServletConfig; import javax.servlet.ServletException; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.output.*; public class UploadServlet extends HttpServlet { private boolean isMultipart; private String filePath; private int maxFileSize = 50 * 1024; private int maxMemSize = 4 * 1024; private File file; public void init() { // Get the file location where it would be stored. filePath = getServletContext().getInitParameter("file-upload"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException("GET method used with " + getClass().getName() + ": POST method required."); } }
三、編譯和運行Servlet
編譯上述Servlet UploadServlet並在web.xml文件中創建所需的條目,如下所示:
<servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping>
現在嘗試使用上面創建的HTML表單來上傳文件。當訪問http://localhost:8080/UploadFile.htm
時,它會顯示如下所示的結果,這將有助於從本地計算機中上傳任何文件。
如果Servelt腳本能正常工作,那麽文件會被上傳到c:\apache-tomcat-5.5.29\webapps\data\
目錄中。
測試工程:https://github.com/easonjim/5_java_example/tree/master/servletbasics/test11
Servlet的文件上傳