標籤:max directory amp iter color roc ... ring file
以下內容引用自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 librariesimport 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的檔案上傳