1. The principle of file upload
1. Prerequisites for file upload:
a. The method of the form form must be post
b. The enctype of the form form must be multipart/form-data (it determines the POST request method and the data type of the request body)
c. The type of input provided in form is file type file upload domain.
2. Use third-party components to achieve file upload
1. commons-fileupload component:
jar: commons-fileupload.jar
commons-io.jar
2. Core class or interface
DiskFileItemFactory: Set the environment
public void setSizeThreshold(int sizeThreshold): Set the buffer size. The default is 10Kb.
When the uploaded file exceeds the buffer size, the fileupload component will upload the file using a temporary file cache
public void setRepository(java.io.File repository): Set the directory where temporary files are stored. By default, the system's temporary file storage directory.
ServletFileUpload: core upload class (main function: parse the body content of the request)
boolean isMultipartContent(HttpServletRequest?request): determines whether the enctype of the user's form is of multipart/form-data type.
List parseRequest(HttpServletRequest request): parse the content in the request body
setFileSizeMax(4*1024*1024);//Set the size of a single uploaded file
upload.setSizeMax(6*1024*1024);//Set the total file size
FileItem: Represents an input field in the form.
boolean isFormField(): Is it a normal field
String getFieldName: Get the field name of the normal field
String getString(): Get the value of a normal field
InputStream getInputStream(): Get the input stream of uploaded fields
String getName(): Get the uploaded file name
Example: First create a file folder in the WEB-INF directory, that is, all files must be uploaded here, which is to avoid direct access by others.
1. Get the real path of files
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2. Set up the environment
DiskFileItemFactory factory = new DiskFileItemFactory();//Where is the default cache and temporary file storage place
3.Judge form delivery method
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("Upload method wrong!"); return; }4. File upload core class
ServletFileUpload upload = new ServletFileUpload(factory); 5. Analyze //Parse List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//Normal field, String fieldName submitted by the form = item.getFieldName();//Field name of the form information String fieldValue = item.getString(); //Form information field value System.out.println(fieldName+"="+fieldValue); }else//File processing { InputStream in = item.getInputStream(); //Upload file name C:/Users/Administrator/Desktop/a.txt String name = item.getName(); //Just just need a.txt String fileName = name.substring(name.lastIndexOf("//")+1); //Build the output stream String storeFile = storePath+"//"+fileName;//Upload the file's save address OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1) { out.write(b, 0, len); } in.close();//Close the stream out.close(); } }Write a form
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP '1.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadServlet2" method="post" enctype="multipart/form-data"> Username<input type="text" name="username"/> <br/> <input type="file" name="f1"/><br/> <input type="file" name="f2"/><br/> <input type="submit" value="Save"/> </form> </body></html>Write a submission servlet: UploadServlet2
package com.liuzhen.upload;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;//Introduction to file upload public class UploadServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Set the encoding request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { //Upload the file String storePath = getServletContext().getRealPath("/WEB-INF/files"); //Set the environment DiskFileItemFactory factory = new DiskFileItemFactory(); //Judge form transmission method form enctype=multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("Upload method is incorrect! "); return; } ServletFileUpload upload = new ServletFileUpload(factory); //Parse List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//Normal field, String fieldName submitted by the form = item.getFieldName();//Field name of the form information String fieldValue = item.getString(); //Form information field value System.out.println(fieldName+"="+fieldValue); }else//File processing { InputStream in = item.getInputStream(); //Upload file name C:/Users/Administrator/Desktop/a.txt String name = item.getName(); //Just just need a.txt String fileName = name.substring(name.lastIndexOf("//")+1); //Build the output stream String storeFile = storePath+"//"+fileName;//Upload the file's save address OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1) { out.write(b, 0, len); } in.close();//Close the stream out.close(); } } } catch (FileUploadException e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}The uploaded file is in the Tomcat application.
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.