1. Analysis of the principle of file upload
1. The necessary prerequisites for file upload
a. The method of the form must be post
b. The enctype property of the form must be of type multipart/form-data.
enctype default value: application/x-www-form-urlencoded
Function: Tell the server to the MIME type of the request text
application/x-www-form-urlencoded: username=abc&password=123
ServletRequest.getParameter(String name); This method is a method that specifically reads this type
multipart/form-data:
2. Use commons-fileupload component to upload files
a. Copy the jar package: commons-fileupload.jar commons-io.jar
b. Implementation principle
3. Garbage code problem
a. Garbage code of ordinary fields
FileItem.getString(String charset); encoding should be consistent with the client
b. The uploaded Chinese file name is garbled.
request.setCharacterEncoding("UTF-8"); encoding must be consistent with the client
4. Specific implementation
The code for the front desk upload.jsp is as follows
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>File Upload</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><form action="${pageContext.request.contextPath}/servlet/UploadServlet3" method="post" enctype="multipart/form-data">name:<input name="name"/><br/>file1:<input type="file" name="f1"/><br/>file2:<input type="file" name="f2"/><br/>input type="submit" value="upload"></form></body></html>Background servlet code
package com.itheima.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.io.UsupportedEncodingException;import java.util.List;import java.util.UUID;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.FileUploadBase;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.FilenameUtils;//Detailed explanation of public class UploadServlet3 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();System.out.print(request.getRemoteAddr());boolean isMultipart = ServletFileUpload.isMultipartContent(request);if(!isMultipart){throw new RuntimeException("Please check the enctype property of your form to confirm that it is multipart/form-data");}DiskFileItemFactory dfif = new DiskFileItemFactory();ServletFileUpload parser = new ServletFileUpload(dfif);// parser.setFileSizeMax(3*1024*1024);// Set the size of a single file upload// parser.setSizeMax(6*1024*1024);//Total size limit when uploading multiple files List<FileItem> items = null;try {items = parser.parseRequest(request);}catch(FileUploadBase.FileSizeLimitExceededException e) {out.write("Uploadfile exceeds 3M");return;}catch(FileUploadBase.SizeLimitExceededException e) {out.write("Total file exceeds 6M");return;}catch(FileUploadException e) {e.printStackTrace(); throw new RuntimeException("Parse upload content failed, please try again");}//Process the requested content if(items!=null){for(FileItem item:items){if(item.isFormField()){processFormField(item);}else{processUploadField(item);}}} out.write("Uploaded successfully! ");}private void processUploadField(FileItem item) {try {String fileName = item.getName();//If(fileName!=null&&!fileName.equals("")){fileName = UUID.randomUUID().toString()+"_"+FilenameUtils.getName(fileName);//Extension String extension = FilenameUtils.getExtension(fileName);//MIME type String contentType = item.getContentType();if(contentType.startsWith("image/")){//Date now = new Date();// DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// // String childDirectory = df.format(now);// Calculate the storage directory according to the hashCode of the file name String childDirectory = makeChildDirectory(getServletContext().getRealPath("/WEB-INF/files/"),fileName);String storeDirectoryPath = getServletContext().getRealPath("/WEB-INF/files/"+childDirectory);File storeDirectory = new File(storeDirectoryPath); if(!storeDirectory.exists()){storeDirectory.mkdirs();}System.out.println(fileName);ite(new File(storeDirectoryPath+File.separator+fileName));//Delete temporary file}}} catch (Exception e) {throw new RuntimeException("Upload failed, please try again");}}// Calculate the stored subdirectory private String makeChildDirectory(String realPath, String fileName) {int hashCode = fileName.hashCode();int dir1 = hashCode&0xf;// Take 1~4 bits int dir2 = (hashCode&0xf0)>>4;// Take 5~8 bits String directory = ""+dir1+File.separator+dir2;File file = new File(realPath,directory);if(!file.exists())file.mkdirs();return directory;}private void processFormField(FileItem item) {String fieldName = item.getFieldName();//field name String fieldValue;try {fieldValue = item.getString("UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException("UTF-8 encoding is not supported");}System.out.println(fieldName+"="+fieldValue);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}5. Regarding temporary documents
a. DiskFileItemFactory
public void setRepository(File repository): Set the directory where temporary files are stored public void setSizeThreshold(int sizeThreshold): Set the cache size
b.
When uploading files, use IO stream to process them yourself. Be sure to delete the temporary file after the stream is closed. FileItem.delete()
It is recommended to use: FileItem.writer(File f). The temporary files will be deleted automatically.
6. Limit the file size
a.
ServletFileUpload.setFileSizeMax(3*1024*1024);//Set the size of a single file upload
b.
ServletFileUpload.setSizeMax(6*1024*1024);//Total size limit when uploading multiple files
The above is the example code for the commons fileupload implementation file upload introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!