Using fileupload Component to Implement File Upload for Java Web Learning Notes

Keywords: Java Apache Attribute JSP

file.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    < title > file upload </title >
</head>
<body>
    <%--
        To realize the file upload function in web development, we need to complete the following two steps:
            1. Add the transfer entry to the web page;
            2. Read the data of the uploaded file in the servlet and keep it locally.

        If you add a transfer entry to the web page?
            The <input type= "file" > label is used to add file upload entries to web pages.
            1. The name attribute of the input entry must be set, otherwise the browser will not send the data of the uploaded file.
            2. The enctype attribute of form form must be set to multipart/form-data, and the method attribute must be set to post mode.
                After setting this value, the browser will attach the file data to the message body of the http request when uploading the file, and use the MIME protocol.
                The uploaded files are described to facilitate the receiver to analyze and process the uploaded data.
    --%>
    <form method="post" action="${pageContext.request.contextPath}/uploadServlet" enctype="multipart/form-data">
        <input type="file" name="fileUpload"><br>
        <input type= "submit" value= "upload">
    </form>
</body>
</html>

UploadServlet.java:

package com.demo.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * FileUpload component provided by Apache is used to upload files.
 * Import the jar package:
 *  commons-fileupload-1.2.2.jar: File upload core jar package
 *  commons-io-1.4.jar: Encapsulation of related tool classes for file processing
 */
@WebServlet(name = "UploadServlet", value = "/uploadServlet")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // Create a File Upload Factory
            FileItemFactory factory = new DiskFileItemFactory();
            // Create core tool classes for file upload
            ServletFileUpload upload = new ServletFileUpload(factory);

            // Set the maximum allowable size of a single file (30M)
            upload.setFileSizeMax(30 * 1024 * 1024);
            // Set the total allowable size of the file upload form (80M)
            upload.setSizeMax(80 * 1024 * 1024);
            // Set encoding for uploading form file names
            upload.setHeaderEncoding("UTF-8");

            // Judgment: Does the current form upload a form for a file?
            if (ServletFileUpload.isMultipartContent(request)){
                // Transform request data into FileItem objects, and encapsulate them with collections
                List<FileItem> list = upload.parseRequest(request);
                // Traverse: Get each uploaded data
                for (FileItem item : list) {
                    // Judgment: Common Form Items (Common Text)
                    if (item.isFormField()){
                        // Get the form element name
                        String fieldName = item.getFieldName();
                        // Get the data corresponding to the form element name
                        String content = item.getString();
                        System.out.println(fieldName + "--" + content);
                    }
                    // Upload File Form Items (File Stream)
                    else{
                        // Gets the form element name (< input > tag name attribute value)
                        String fieldName = item.getFieldName();     // fieldName = "file";
                        System.out.println(fieldName);
                        // Get the uploaded file name
                        String name = item.getName();               // name = "aa.txt";
                        // Get the data in the uploaded file
                        String content = item.getString();          // content = "aaa";
                        // Get the file type
                        String contentType = item.getContentType(); // contentType = "text/plain";

                        // Get the uploaded file stream
                        InputStream inputStream = item.getInputStream();
                        // Get the upload base path
                        String path = getServletContext().getRealPath("/upload");
                        // path = "D:\\application\\IDEA\\workspace\\08_file\\out\\artifacts\\08_file_war_exploded\\upload"

                        // Specify the path to be saved locally
                        String filePath = "D://test.txt";
                        // Create target file objects
                        File file = new File(filePath);
                        // Save the file locally
                        item.write(file);
                        // Delete temporary files generated by the system
                        item.delete();
                    }
                }
            }else{
                System.out.println("The current form is not a file upload form!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

 

Posted by micknc on Sat, 05 Oct 2019 11:36:15 -0700