Generally, when using Servlet to process form elements, the form elements are all simple text, and Servlets are easy to process with Request.getParameter(). But when the form contains more than just some simple text, such as uploading file fields, it is still a very complicated task to parse each sub-part of the composite form directly from the HttpServletRequest object.
In order to simplify the processing of "multipart/form-data" type data, corresponding components can be used for processing, which can save a lot of coding, support reuse, and is also very efficient.
There are also some Java components: FileUpload, SmartUpload, Cos, etc. This article will explain it with Apache's FileUpload.
To use FileUpload, you should first download the corresponding component:
1.fileupload package: http://commons.apache.org/fileupload/
2.io package: http://commons.apache.org/io/
After downloading, unzip the zip package and copy commons-fileupload-1.2.1.jar and commons-io-1.4.jar to tomcat's webapp/WEB-INF/lib.
1. Form page (to specify the enctype="multipart/form-data" of the form) - Upload.html
<html><head><title>Upload</title></head><body > <form name="uploadForm" method="POST" enctype="MULTIPART/FORM-DATA" action="upload"> <table> <tr> <td><div align="right">User Name:</div></td> <td><input type="text" name="username" size="30"/> </td> </tr> <tr> <td><div align="right">Upload File1:</div></td> <td><input type="file" name="file1" size="30"/> </td> </tr> <tr> <td><div align="right">Upload File2:</div></td> <td><input type="file" name="file2" size="30"/> </td> </tr> <tr> <td><input type="submit" name="submit" value="upload"></td> <td><input type="reset" name="reset" value="reset"></td> </tr> </table> </form></body></html>
2. Servlet processing form - UploadServlet
package mypack;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; // directory where uploaded files is private String tempFilePath; // directory where temporary files are stored public void init(ServletConfig config)throws ServletException { super.init(config); filePath=config.getInitParameter("filePath"); tempFilePath=config.getInitParameter("tempFilePath"); filePath=getServletContext().getRealPath(filePath); tempFilePath=getServletContext().getRealPath(tempFilePath); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); //Send response body to the client PrintWriter outNet=response.getWriter(); try{ //Create a hard disk-based FileItem factory DiskFileItemFactory factory = new DiskFileItemFactory(); //Set the size of the buffer used to write data to the hard disk, here is 4K factory.setSizeThreshold(4*1024); //Set the temporary directory factory.setRepository(new File(tempFilePath)); //Create a file upload processor ServletFileUpload upload = new ServletFileUpload(factory); //Set the maximum size of the file allowed to be uploaded, here is 4M upload.setSizeMax(4*1024*1024); List /* FileItem */ items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if(item.isFormField()) { processFormField(item,outNet); //handle ordinary form fields}else{ processUploadedFile(item,outNet); //handle upload files} } outNet.close(); }catch(Exception e){ throw new ServletException(e); } } private void processFormField(FileItem item,PrintWriter outNet){ String name = item.getFieldName(); String value = item.getString(); outNet.println(name+":"+value+"/r/n"); } private void processUploadedFile(FileItem item,PrintWriter outNet)throws Exception{ String filename=item.getName(); int index=filename.lastIndexOf("//"); filename=filename.substring(index+1,filename.length()); long fileSize=item.getSize(); if(filename.equals("") && fileSize==0)return; File uploadedFile = new File(filePath+"/"+filename); item.write(uploadedFile); outNet.println(filename+" is saved."); outNet.println("The size of " +filename+" is "+fileSize+"/r/n"); }} The Servlet is configured in Web.xml as:
<servlet> <servlet-name>upload</servlet-name> <servlet-class>mypack.UploadServlet</servlet-class> <init-param> <param-name>filePath</param-name> <param-value>store</param-value> </init-param> <init-param> <param-name>tempFilePath</param-name> <param-value>temp</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping>
At this point, a simple file upload function has been completed - access the form page, select the file and click upload the file. If you want to save the file to the database while uploading the file to the server, you can save the file name to the database after obtaining the file name, so that you can select the user's file according to the file name in the future!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.