SpringBoot upload file

Posted by suncore on Fri, 25 Feb 2022 04:07:58 +0100

Uploading files should be the most frequently encountered scenario. Today, let's simply do a Spring Boot file uploading function with you. Without much nonsense, let's start directly.

The project structure is as follows:

pom dependency

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
       <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Upload control class

@Controller
public class UploadController
{
    private static String UPLOADED_FOLDER = "D:\\uploadFile\\";

    @GetMapping("/")
    public String index()
    {
        return "upload";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes)
    {
        if (file.isEmpty())
        {
            redirectAttributes.addFlashAttribute("message", "Please select file upload");
            return "redirect:uploadStatus";
        }

        try
        {
            byte[] bytes = file.getBytes();
            Path dir = Paths.get(UPLOADED_FOLDER);
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            if (!Files.exists(dir))
            {
                Files.createDirectories(dir);
            }
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message","Upload succeeded, file name:" + file.getOriginalFilename());

        }
        catch (IOException e)
        {
            redirectAttributes.addFlashAttribute("message", "Service exception");
            e.printStackTrace();
        }
        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus()
    {
        return "uploadStatus";
    }
}

Read the file information through MultipartFile. If the file is empty, jump to the result page and give a prompt; If it is not empty, read the file stream and write it to the specified directory, and finally display the results on the page.

MultipartFile is the encapsulation class of Spring upload file, which contains the binary stream and file attributes of the file. The related attributes can also be configured in the configuration file.

  • spring.http.multipart.enabled=true # supports file upload by default
  • spring. http. multipart. File size threshold = 0 # supports writing files to disk
  • spring.http.multipart.location = # temporary directory of uploaded files
  • spring. http. multipart. Max file size = 1MB # maximum supported file size
  • spring. http. multipart. Max request size = 10MB # maximum support request size

The last two configuration contents are most commonly used, which limit the file upload size. If the size is exceeded, an exception will be thrown.

configuration file

application.properties

server.port=8086
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

exception handling

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";
    }
}

Set a @ ControllerAdvice to monitor whether the file size uploaded by Multipart is limited. When this exception occurs, a prompt will be given on the front page.

Front page

upload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Upload file</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
</body>
</html>

uploadStatus.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Upload status</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

test

  • Start the project, enter localhost:8086 in the browser, and the display is as follows:

  • Choose a file to upload. Here I choose a picture

  • Click Submit to display the successful upload.

  • View the picture in the local folder D:\uploadFile \. So far, the upload function has been realized.

Large file upload

  • Test the file upload results that exceed the set 10M. As shown in the figure below, the problem of connection reset occurs when the uploaded file is greater than 10M, and the exception content GlobalException cannot be captured.

Tomcat connection reset

If deploying to tomcat, configure maxSwallowSize to avoid this Tomcat connection reset problem. For embedded tomcat, declare a TomcatEmbeddedServletContainerFactory with the following code:

package com.cy;

import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringbootUploadApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(SpringbootUploadApplication.class, args);
    }

    @Bean
    public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }

}

Upload the file exceeding the size limit again, and the page throws an exception as follows:

summary

The simple demo of springboot uploading files has been completed, and there are many files to upload. Little friends can also try it by themselves.

Topics: Java Spring Boot