Servlet file upload
Servlet can be used with the HTML form tag to allow users to upload files to the server. The uploaded file can be a text file or an image file or any document.
Create a file upload form
The following HTML code creates a file upload form. The following points need to be noted:
The form method attribute should be set to the POST method, and the GET method cannot be used.
Formenctype The property should be set to multipart/form-data.
form# The ##action attribute should be set to the Servlet file that handles file uploads on the backend server. The following example uses UploadServlet Servlet to upload files.
- To upload a single file, you should use a single <input .../> tag with the attribute type="file". To allow multiple file uploads, include multiple input tags with different name attribute values. Input tags have different values for the name attribute. The browser associates a browse button with each input tag.
<html> <head> <title>文件上传表单</title> </head> <body> <h3>文件上传:</h3> 请选择要上传的文件:<br /> <form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" size="50" /> <br /> <input type="submit" value="上传文件" /> </form> </body> </html>This will display the following results, allowing the user to select a file from the local computer. When the user clicks "Upload File", the form will be submitted along with the file selected from the local computer:
<b>文件上传:</b> 请选择要上传的文件:<br /> <input type="file" name="file" size="50" /> <br /> <input type="button" value="上传文件" /> <br /> 注:这只是虚拟的表单,不会正常工作。Writing background ServletThe following is the Servlet
UploadServlet, which will accept the uploaded file and store it in the directory <Tomcat-installation-directory>/webapps/ in data. This directory name can also be added using external configuration, such as the context-param element in web.xml, as shown below:
<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>The following is the source code of UploadServlet, which can process multiple files at once Upload of files. Before proceeding, please confirm the following:
- The example below depends on FileUpload, so be sure to have the latest version of
commons-fileupload on your classpath. x.x.jar file. Can be downloaded from http://commons.apache.org/fileupload/.
- FileUpload relies on Commons IO, so be sure to have the latest version of the
commons-io-x.x.jar file in your classpath. Can be downloaded from http://commons.apache.org/io/.
- When testing the following example, the size of the file you upload cannot be larger than
maxFileSize, otherwise the file will not be uploaded.
- Please ensure that the directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data have been created in advance.
// 导入必需的 java 库 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( ){ // 获取文件将被存储的位置 filePath = getServletContext().getInitParameter("file-upload"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // 检查我们有一个文件上传请求 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(); // 文件大小的最大值将被存储在内存中 factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\temp")); // 创建一个新的文件上传处理程序 ServletFileUpload upload = new ServletFileUpload(factory); // 允许上传的文件大小的最大值 upload.setSizeMax( maxFileSize ); try{ // 解析请求,获取文件项 List fileItems = upload.parseRequest(request); // 处理上传的文件项 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 () ) { // 获取上传文件的参数 String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // 写入文件 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."); } }Compile and run the ServletCompile the above Servlet UploadServlet and create the required entries in the web.xml file as follows:
<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>Now try to upload a file using the HTML form you created above. When you visit: http://localhost:8080/UploadFile.htm in your browser, it will display the following result, which will help you to upload any file from your local computer.
<b>文件上传:</b> 请选择要上传的文件:<br /> <input type="file" name="file" size="50" /> <br /> <input type="button" value="上传文件" />If your Servelt script works properly, your files will be uploaded to the c:\apache-tomcat-5.5.29\webapps\data\ directory.