The article directories

    • preface
    • Commons FileUpload
    • Using the Servlet 3.0
    • Uploading a single file
    • Multiple file uploads
    • Upload a file with other form data
    • Spring Boot Starts uploading files

preface

Spring allows us to enable multipart support using pluggable MultipartResolver objects. The framework provides

  • A MultipartResolver implementation of Commons FileUpload
  • And another implementation for Servlet 3.0 multi-part request resolution

Commons FileUpload

To use CommonsMultipartResolver to handle file uploads, we need to add the following dependencies:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
Copy the code

We can now define the CommonsMultipartResolver bean in our Spring configuration.

The MultipartResolver comes with a set of set methods that define properties such as the maximum upload size:

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver(a) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);
    return multipartResolver;
}
Copy the code

Here, we need to control the different properties of CommonsMultipartResolver in the Bean definition itself.

Using the Servlet 3.0

To use Servlet 3.0 multi-part parsing, we need to configure several applications. First we need to set the MultipartConfigElement in the DispatcherServlet registry:

public class MainWebAppInitializer implements WebApplicationInitializer {

    private String TMP_FOLDER = "/tmp"; 
    private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; 
    
    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        
        ServletRegistration.Dynamic appServlet = sc.addServlet("mvc".new DispatcherServlet(
          new GenericWebApplicationContext()));

        appServlet.setLoadOnStartup(1);
        
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, 
          MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); appServlet.setMultipartConfig(multipartConfigElement); }}Copy the code

In the MultipartConfigElement object, we configure

  • Storage location
  • Maximum single file size
  • Maximum request size (in case of multiple files in a single request)
  • And the size of the file upload progress to the storage location.

These Settings must be applied at the Servlet registration level, because Servlet 3.0 does not allow them to be registered in MultipartResolver like CommonsMultipartResolver.

After completion of the operation, we can add StandardServletMultipartResolver into our Spring configuration:

@Bean
public StandardServletMultipartResolver multipartResolver(a) {
    return new StandardServletMultipartResolver();
}
Copy the code

Uploading a single file

To upload a file, we can build a simple form with an HTML input tag of type ‘file’.

Whichever upload processing configuration we choose, we need to set the form’s encoding property to multipart/form-data, which lets the browser know how to encode the form:

<form:form method="POST" action="/spring-mvc-xml/uploadFile" enctype="multipart/form-data">
    <table>
        <tr>
            <td><form:label path="file">Select a file to upload</form:label></td>
            <td><input type="file" name="file" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form>
Copy the code

To store uploaded files, we can use the MultipartFile variable. We can retrieve this variable from the request parameter inside the controller method:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") MultipartFile file, ModelMap modelMap) {
    modelMap.addAttribute("file", file);
    return "fileUploadView";
}
Copy the code

The MultipartFile class provides access to detailed information about uploaded files, including filename, file type, and so on. We can use a simple HTML page to display this information:

<h2>Submitted File</h2>
<table>
    <tr>
        <td>OriginalFileName:</td>
        <td>${file.originalFilename}</td>
    </tr>
    <tr>
        <td>Type:</td>
        <td>${file.contentType}</td>
    </tr>
</table>
Copy the code

Multiple file uploads

To upload multiple files in a single request, we simply place multiple input file fields in the form:

<form:form method="POST" action="/spring-mvc-java/uploadMultiFile" enctype="multipart/form-data">
    <table>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="files" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form:form>
Copy the code

We need to note that each input field has the same name so that it can be accessed as a MultipartFile array:

@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public String submit(@RequestParam("files") MultipartFile[] files, ModelMap modelMap) {
    modelMap.addAttribute("files", files);
    return "fileUploadView";
}
Copy the code

Now, we can simply iterate through the array to display file information:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Spring MVC File Upload</title>
    </head>
    <body>
        <h2>Submitted Files</h2>
        <table>
            <c:forEach items="${files}" var="file">    
                <tr>
                    <td>OriginalFileName:</td>
                    <td>${file.originalFilename}</td>
                </tr>
                <tr>
                    <td>Type:</td>
                    <td>${file.contentType}</td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>
Copy the code

Upload a file with other form data

We can also send other information to the server as well as the files we are uploading. We just need to include required fields in the form:

<form:form method="POST" 
  action="/spring-mvc-java/uploadFileWithAddtionalData"
  enctype="multipart/form-data">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" name="name" /></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input type="text" name="email" /></td>
        </tr>
        <tr>
            <td>Select a file to upload</td>
            <td><input type="file" name="file" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form:form>
Copy the code

In the controller, we can get all the form data using the @requestParam annotation:

@PostMapping("/uploadFileWithAddtionalData")
public String submit(
  @RequestParam MultipartFile file, @RequestParam String name,
  @RequestParam String email, ModelMap modelMap) {

    modelMap.addAttribute("name", name);
    modelMap.addAttribute("email", email);
    modelMap.addAttribute("file", file);
    return "fileUploadView";
}
Copy the code

Similar to the previous section, we can use HTML pages with JSTL tags to display information.

We can also wrap all the form fields in model classes and use @ModelAttribute annotations in the controller. This is helpful when there are many other fields in the file. Let’s look at the code:

public class FormDataWithFile {

    private String name;
    private String email;
    private MultipartFile file;

    // standard getters and setters
}
@PostMapping("/uploadFileModelAttribute")
public String submit(@ModelAttribute FormDataWithFile formDataWithFile, ModelMap modelMap) {

    modelMap.addAttribute("formDataWithFile", formDataWithFile);
    return "fileUploadView";
}
Copy the code

Spring Boot Starts uploading files

Spring Boot makes configuring and starting everything much easier.

As long as we include the Web module in our dependencies, Boot will register and configure it for us,

Boot has clearly configured us with an implementation for Servlet 3.0 multi-part request resolution

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.1.8. RELEASE</version>
</dependency>
Copy the code

Edit if you want to control the maximum file upload sizeapplication.properties:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
Copy the code

We can also control whether file uploads are enabled and where files are uploaded:

spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tmpdir}
Copy the code

Please note that we have used$ {java.io.tmpdir}Upload locations are defined so that temporary locations can be used for different operating systems.

Reference: www.baeldung.com/spring-file…


🍎QQ group [837324215] 🍎 pay attention to my public number [Java Factory interview officer], learn together 🍎🍎🍎