Multipart Resolver

From org. Springframework. Web. Multipart package under the MultipartResolver provide parsing multipart request strategies, including file upload. One approach is based on Commons FileUpload, the other is based on Servlet 3.0 multi-part request resolution.

To enable multi-part processing, you need to declare a MultipartResolverbean named multipartResolver in the DispatcherServletSpring configuration. The DispatcherServlet detects it and applies it to incoming requests. When receiving a content-type is multipart/form – data POST requests, parsing program parses the content and the current it packaging for MultipartHttpServletRequest, To provide access to the parsed part, in addition to exposing it as a request parameter.

Apache Commons FileUpload

To use Apache Commons FileUpload, configure the CommonsMultipartResolver type Bean named multipartResolver. You also need to introduce a commons-Fileupload dependency.

The Servlet 3.0

Enabling multi-part parsing for Servlet 3.0 requires configuration through the Servlet container. The operation is as follows:

  • Through Java configuration, set one in the Servlet registryMultipartConfigElement.
  • Through web.xml, add to the servlet definition<multipart-config>Part.

Code implementation

Spring MVC environment configuration

Build a Maven-ArchetypeWeb-app project using MAVEN and configure SpringMVC in Java code form as follows:

Pom.xml, introducing dependencies

<properties> ... <spring.version>5.2.2.RELEASE</spring.version> <tomcat.version>8.5.5</tomcat.version> </properties> <dependencies> <! --spring -core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <! --web--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> The < version > 3.1.0 < / version > < scope > provided < / scope > < / dependency > < / dependencies >Copy the code

Spring MVC configuration

AppConfig.java

@Configuration
@ComponentScan("io.github.nirvanafire")
public class AppConfig implements WebMvcConfigurer {
    ...
}
Copy the code

MyWebApplicationInitializer.java

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024;

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("---MyApplicationInitializer onStartup---"); / / load the Spring Web application configuration AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext (); ac.register(AppConfig.class); ac.refresh(); Ds = new DispatcherServlet(AC); ServletRegistration.Dynamic registration = servletContext.addServlet("dispatchServlet", ds);
        registration.setLoadOnStartup(1);
        registration.addMapping("*.do"); }}Copy the code

File upload Controller implementation

@RestController
public class UploadController {

    @PostMapping("/upload_commons")
    public String uploadCommons(@RequestPart("file") MultipartFile file) {

        System.out.println("---Run Upload Commons---");
        storeFile(file);
        return "success";
    }

    private void storeFile(MultipartFile file) {
        try {

            String originalFilename = file.getOriginalFilename();
            System.out.println("----File Name: " + originalFilename + "--");

            File tmpFolder = new File("tmp");
            if(! tmpFolder.exists()) { tmpFolder.mkdir(); } File tmp = new File("tmp/" + originalFilename);
            FileOutputStream fos = new FileOutputStream(tmp);
            FileCopyUtils.copy(file.getInputStream(), fos);
        } catch (IOException e) {
            System.out.println("Upload File Error: "+ e.getMessage()); }}}Copy the code

Page code

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringMVC-UploadFile</title>
</head>
<body>
    <h1>SpringMVC-UploadFile</h1>

    <hr>
    <h2>Apache Commons FileUpload</h2>
    <form action="/upload_commons.do" enctype="multipart/form-data" method="post">
        <input type="file" name="file">
        <input type="submit" value="Submit">
    </form>
 
</body>
</html>
Copy the code

Apache Commons FileUpload

Add Apache Commons FileUpload dependencies to the pop.xml file:

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

Declare a CommonsMultipartResolver Bean named multipartResolver in Appconfig. Java.

@Configuration
@ComponentScan("io.github.nirvanafire")
public class AppConfig implements WebMvcConfigurer {
    ...
    @Bean("multipartResolver")
    public CommonsMultipartResolver commonsMultipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        returncommonsMultipartResolver; }}Copy the code

The Servlet 3.0

At the Servlet in the registry Settings a MultipartConfigElement, namely in MyWebApplicationInitializer. Add the following code in Java:

private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    ...
    System.out.println("---tmpdir: "  + System.getProperty("java.io.tmpdir") + "-");
    File uploadDirectory = new File(System.getProperty("java.io.tmpdir")); /** * MultipartConfigElement Parameter Meaning * @param location The directory locationwhereFiles will be stored * @param maxFileSize the maximum size allowedforAfter the event files are uploaded the maximum size allowedforMultipart /form-data requests @param fileSizeThreshold The size threshold afterwhichFiles will (Threshold for files to be written to disk, MultipartConfigElement MultipartConfigElement = new MultipartConfigElement(uploadDirectory.getAbsolutePath(), MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); registration.setMultipartConfig(multipartConfigElement); }Copy the code

The AppConfig. A name for the multipartResolver StandardServletMultipartResolver declaration in the Java Bean.

@Configuration
@ComponentScan("io.github.nirvanafire")
public class AppConfig implements WebMvcConfigurer {
    ...
    @Bean("multipartResolver")
    public StandardServletMultipartResolver standardServletMultipartResolver() {
        StandardServletMultipartResolver standardServletMultipartResolver = new StandardServletMultipartResolver();
        returnstandardServletMultipartResolver; }}Copy the code

summary

Whether FileUpload or Servlet 3.0 implements multi-part parsing, Need in the configuration of DispatcherServletSpring declare a named multipartResolver MultipartResolverbean (FileUpload statement CommonsMultipartResolver, Servlet 3.0 statement StandardMultipartResolver), with a qualified statement bean name (multipartResolver), restrict the more part of the project is only one way to achieve

A link to the

  • Spring MVC Multipart Resolver
  • Code link