Spring MVC learning notes [part5] local file upload

Spring MVC learning notes Part5

1. Principle of file upload

This section will review the traditional file upload methods of Java Web and learn the more convenient file upload components provided by spring MVC. First, let's review some pre knowledge of file upload.

  1. The enctype value of the form must be: multipart / form data (the default value is: application/x-www-form-urlencoded). Enctype is the type of the form request body. The multipart attribute indicates that the request body will be divided into several parts.
  2. The method property value of the form must be Post.
  3. A file selection field < input type = "file" / > should be provided in the form
<form action="user/fileupload" method="post" enctype="multipart/form-data"> 
    Select File:<input type="file" name="upload"/><br/> 
    <input type="submit" value="Upload file"/> 
</form>

Note: when the enctype value of the form is not the default value, request Getparameter() will fail.

When the enctype value of the form is "application/x-www-form-urlencoded", the body content of the form is: key = value & key = value & key = value.

When the enctype value of the form form is "mutilpart / form data", the content of the request body will become the body described by MIME type in each part: resolver, protocol header, protocol body and protocol type (MIME type).

2. Traditional file upload

First, import the file and upload the relevant coordinates.

<dependency> 
    <groupId>commons-fileupload</groupId> 
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version> 
</dependency>
<dependency> 
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Write the controller method for file upload.

@RequestMapping(value="/myUpload")
public String myUpload(HttpServletRequest request) throws Exception { 
    // Get the file directory to upload first 
    String path = request.getSession().getServletContext().getRealPath("/uploads"); 
    // Create a File object and upload the File to this path 
    File file = new File(path); 
    // Judge whether the path exists. If it does not exist, create the path 
    if(!file.exists()) {
        file.mkdirs(); 
    }
    
    // Create a disk file item factory, and then use the factory to create a file upload parser
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory); 
    // Parse the request object to get the collection of file items
    List<FileItem> items = fileUpload.parseRequest(request); 
    
    // ergodic 
    for (FileItem item : items) { 
        // Judge whether the file item is a common field or an uploaded file 
        if(item.isFormField()) { 
            //Description is a normal form item
        }else { 
            // Description is the upload file item
            // Gets the name of the uploaded file 
            String filename = item.getName();
            // Make the name of the file unique 
            String uuid = UUID.randomUUID().toString().replaceAll("-", ""); 
            filename = uuid+"_"+filename;
            // Upload file 
            item.write(new File(file, filename)); 
            // Delete temporary files (when it is less than 10kb, the server will automatically clear after uploading. When it is more than 10kb, there will be temporary files after uploading, which need to be cleared by itself)
            item.delete(); 
        } 
    }
    return "success"; 
}

3. File upload of spring MVC framework

First, briefly describe the basic principle of file upload of spring MVC framework: first, we need a MultipartFile class object provided by the framework. When we click submit, the request will be sent to the front-end Controller. The front-end Controller will send the request to the configuration file parser for parsing. After parsing, an upload file upload item will be returned to the front-end Controller, and the front-end Controller will send the upload to the method we wrote in the Controller.

How to create MultipartFile class objects is also very simple. The first step is to configure and create the configuration in xml into the IoC container. Secondly, just add the formal parameters in the controller method for file upload.

Step 1: create CommonsMultipartResolver into IoC container.

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"/>
</bean>

Note that for the bean creation of CommonsMultipartResolver, the id attribute value must be multipartResolver. Other will cause an HTTP 500 error.

Step 2: write the controller method for file upload, add the parameters of MultipartFile, and write the file upload code.

@RequestMapping("myUpload")
public String myUpload(HttpServletRequest request,MultipartFile upload) throws Exception {
    // Get the file directory to upload first
    String path = request.getSession().getServletContext().getRealPath("/uploads");
    // Create a File object and upload the File to this path later
    File file = new File(path);
    // Judge whether the path exists. If it does not exist, create the path
    if (!file.exists()) {
        file.mkdirs();
    }

    // Upload is parsed by spring MVC. It is an upload file item that can be used directly
    // Change 1 Gets the name of the uploaded file
    String filename = upload.getOriginalFilename();
    // Make the name of the file unique
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    filename = uuid + "_" + filename;
    // Change 2 Complete file upload
    upload.transferTo(new File(path,filename));

    return "success";
}

Compared with the traditional file upload method, it simplifies two codes and eliminates the traversal operation.

Keywords: Java Front-end server Spring MVC

Added by Markto on Sat, 22 Jan 2022 20:47:01 +0200