1. Required packages:
1. commons-fileupload-1.2.1.jar:
Download address
http://commons.apache.org/downloads/download_fileupload.cgi
2. commons-io-1.4.jar:
Download address
http://commons.apache.org/downloads/download_io.cgi
2. Notes:
Enctype="multipart/form-data" should be added to the form form
3. Code examples
1. jsp code:
<%@ 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>upload</title> </head> <body> <form action="uploadServlet" method="post" enctype="multipart/form-data"> <table> <caption>Upload instance</caption> <tr> <td>Name</td> <td> <input type="text" name="name"> </td> </tr> <tr> <td>Age</td> <td> <input type="text" name="age"> </td> </tr> <tr> <td>Photo</td> <td> <input type="file" name="image"> </td> </tr> <tr> <td></td> <td> <input type="submit" value="Submit"> </td> </tr> </table> </form> </body> </html>
2. UploadServlet Code
package servlet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; /** * Upload servlet * @author lisanlai * */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // Set the character encoding to UTF-8, so that Chinese character display response.setCharacterEncoding("UTF-8"); Writer o = response.getWriter(); /** * First, determine whether the form enctype is multipart/form-data * At the same time, it also determines whether the form's submission method is post * Method: isMultipartContent(request) */ if(ServletFileUpload.isMultipartContent(request)){ request.setCharacterEncoding("utf-8"); // Instantiate a hard disk file factory to configure the upload component ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); // Set the temporary folder for file storage, this folder must really exist File fileDir = new File("../webapps/fileupload/tmp/"); if(fileDir.isDirectory() && fileDir.exists()==false){ fileDir.mkdir(); } factory.setRepository(fileDir); //Set the maximum memory occupied factory.setSizeThreshold(1024000); //Create ServletFileUpload object ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setHeaderEncoding("utf-8"); //Set the maximum value of a single file byte sfu.setFileSizeMax(102400000); //The sum of all uploaded files is maximum byte sfu.setSizeMax(204800000); List<FileItem> items = null; try { items = sfu.parseRequest(request); } catch (SizeLimitExceededException e) { System.out.println("File size exceeds the maximum"); } catch(FileUploadException e) { e.printStackTrace(); } //Get the iterator of items Iterator<FileItem> iter = items==null?null:items.iterator(); //Path directory stored after image upload File images = new File("D:/upload/images/"); if(images.exists()==false){ images.mkdirs(); } //Iteration items while(iter!=null && iter.hasNext()){ FileItem item = (FileItem) iter.next(); //If the passed is an ordinary form field if(item.isFormField()){ System.out.print("ordinary form field:"); System.out.print(new String(item.getFieldName()) + " "); System.out.println(new String(item.getString("UTF-8"))); } //File field else if(!item.isFormField()){ System.out.println("Source picture:" + item.getName()); String fileName = item.getName().substring(item.getName().lastIndexOf("//")); BufferedInputStream in = new BufferedInputStream(item.getInputStream()); //The file is stored in the D:/upload/images directory, and this directory must also have BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(images.getAbsolutePath()+ fileName))); Streams.copy(in, out, true); o.write("File upload successful"); } } } } else { System.out.println("Form enctype type error"); } } } } } 3. web.xml
<?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" 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"> <display-name>UploadTest</display-name> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
This article has been compiled into "Summary of Java Upload Operation Techniques", and everyone is welcome to learn and read.
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.