Java file upload: common file upload upload component

Reference Reprint:


The common fileUpload component uses the DiskFileItemFactory factory method to generate a request form content parser, which parses the form content into a list < fileitem >, and then circularly obtains the input stream getInputStream() to process the uploaded file.


1. Check save directory and temporary file save directory

2. Create DiskFileItemFactory factory factory

3. Create a servlet file upload parser with the factory

4. Determine whether the submitted data is the data of the uploaded form, that is, whether it is enctype = "multipart / form data"

5. Use the ServletFileUpload parser to parse the uploaded data. The result of parsing returns the list < FileItem > collection. The FileItem corresponds to the input item of the Form form

6. Loop through every FileItem

7. If it is a normal form input item, get the form field and form content

8. If it is a file upload item, get the processing file name, getInputStream(), and save it to the save directory



<%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <title>fileupload test</title>
    <form action="${pageContext.request.contextPath}/servlet/uploadHandleServlet" method="post" enctype="multipart/form-data">
        Upload user:<input type="text" name="username"><br>
        Upload file 1:<input type="file" name="file1"><br>
        Upload file 2:<input type="file" name="file2"><br>
        <input type="submit" value="submit">
package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import sun.swing.FilePane;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.UUID;

public class uploadHandleServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File saveFile = new File(savePath);
        if (!saveFile.exists() && !saveFile.isDirectory()) {
            System.out.println("Directory or file does not exist");
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File tempFile = new File(tempPath);
        if (!tempFile.exists() && !tempFile.isDirectory()) {
            System.out.println("Directory or file does not exist");
        //Message hint
        String message = "";
        try {
            //Using fileupload to upload files is not available
            //1. Create a DiskFileItemFactory factory
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(1024 * 10);//Set the buffer size of the factory. When the uploaded file size exceeds the buffer size, a temporary file will be generated and stored in the specified temporary directory.
            diskFileItemFactory.setRepository(tempFile);//Set the save directory of temporary files generated during upload
            //2. Using factory to create file upload parser
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            servletFileUpload.setHeaderEncoding("UTF-8");//Solve the Chinese code of uploaded file name
            servletFileUpload.setProgressListener(new ProgressListener() {
                public void update(long pBytesRead, long pContentLength, int i) {
                    System.out.println("The file size is:" + pContentLength + ",Currently processed:" + pBytesRead);
            //3. Determine whether it is form data
            if (!servletFileUpload.isMultipartContent(request)) {
            servletFileUpload.setFileSizeMax(1024 * 1024);//Set the maximum size of the uploaded single file
            servletFileUpload.setSizeMax(1024 * 1024 * 10);//Set the maximum value of the total number of uploaded files. The maximum value = the sum of the maximum sizes of multiple files uploaded at the same time
            //4. Use the ServletFileUpload parser to parse the uploaded data. The result of parsing returns a list < FileItem > collection. Each FileItem corresponds to an input item of a Form form
            List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
            for (FileItem item : fileItemList) {
                //If the data encapsulated in fileitem is the data of normal input item
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");//To solve the problem of Chinese scrambling for data of common input items
                    System.out.println(name + "  " + value);
                } else {
                    String fileName = item.getName();//If the file item encapsulates the uploaded file, the name of the uploaded file will be obtained
                    System.out.println("File name:" + fileName);
                    if (fileName == null || fileName.trim().equals("")) {
                    fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);//ie browser may have path
                    String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if ("zip".equals(fileExtName) || "rar".equals(fileExtName) || "tar".equals(fileExtName) || "jar".equals(fileExtName)) {
                        request.setAttribute("message", "Upload file type does not match");
                        request.getRequestDispatcher("/fileupload/message.jsp").forward(request, response);
                    System.out.println("Extension of the uploaded file:" + fileExtName);
                    fileName = UUID.randomUUID().toString() + "_" + fileName;
                    System.out.println("Save path as:" + savePath);

//                    Read in normal IO mode
//                    InputStream is = item.getInputStream();
//                    FileOutputStream fos=new FileOutputStream(savePath+File.separator+fileName);
//                    byte[] buffer = new byte[1024];
//                    int length=0;
//                    while ((length = > 0) {
//                        fos.write(buffer,0,length);
//                    }

                    //NIO mode read
                    InputStream is = item.getInputStream();
                    ReadableByteChannel readChannel = Channels.newChannel(is);
                    FileOutputStream fos = new FileOutputStream(savePath + File.separator + fileName);
                    WritableByteChannel writeChannel = Channels.newChannel(fos);
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int length = 0;
                    while ((length = > 0) {
                        buffer.flip();//Buffer cursor flip to 0

                    message = "File uploaded successfully";

        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            request.setAttribute("message", "Single file exceeds maximum");
            request.getRequestDispatcher("/fileupload/message.jsp").forward(request, response);
        } catch (FileUploadBase.SizeLimitExceededException e) {
            request.setAttribute("message", "The total size of the uploaded file exceeds the maximum limit!!!");
            request.getRequestDispatcher("/fileupload/message.jsp").forward(request, response);
        } catch (FileUploadException e) {
            message = "File upload failed";
        } catch (Exception e) {
            message = e.getMessage();
        request.setAttribute("message", message);
        request.getRequestDispatcher("/fileupload/message.jsp").forward(request, response);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



<%@ page contentType="text/html;charset=UTF-8" language="java" %>









Published 38 original articles, won praise 11, visited 110000+
Private letter follow

Tags: Java JSP Apache IE

Posted on Wed, 05 Feb 2020 10:59:44 -0500 by toibs