Uploading files is one of the scenarios often applied in the Internet. The most typical situation is uploading profile pictures, etc. Today, I will take you to do a small case of uploading files by Spring Boot.

1. Pom package configuration

We used the latest Spring Boot version 1.5.9, JDK 1.8, tomcat8.0.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9. RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<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>
</dependencies>
Copy the code

Spring-boot-starter -thymeleaf as a page template engine, write some simple upload examples.

2. Start class Settings

@SpringBootApplication
public class FileUploadWebApplication {

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

    //Tomcat large file upload connection reset
    @Bean
    public TomcatEmbeddedServletContainerFactory tomcatEmbedded(a) {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceofAbstractHttp11Protocol<? >)) {//-1 means unlimited((AbstractHttp11Protocol<? >) connector.getProtocolHandler()).setMaxSwallowSize(-1); }});returntomcat; }}Copy the code

TomcatEmbedded is a code that solves the problem of connection resetting when uploading files larger than 10M. This exception content is also not caught by GlobalException.

Tomcat Large File Upload Connection reset

3. Write front-end pages

The upload page


      
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</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>
Copy the code

A very simple Post request, a checkbox to select a file, and a submit button, looks like this:

Upload result display page:


      
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Upload Status</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>
Copy the code

The renderings are as follows:

4. Write upload control classes

Access localhost automatically redirects to upload page:

@GetMapping("/")
public String index(a) {
    return "upload";
}
Copy the code

Upload Service Processing

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

    try {
        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
        Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
        Files.write(path, bytes);

        redirectAttributes.addFlashAttribute("message"."You successfully uploaded '" + file.getOriginalFilename() + "'");

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "redirect:/uploadStatus";
}
Copy the code

Read file information through MultipartFile, jump to the result page if the file is empty and give a hint; If the file stream is not read empty and written to the specified directory, the results are finally displayed on the page.

MultipartFile is the encapsulation class of Spring uploaded files. It contains information about the binary stream and file properties. You can also configure related properties in the configuration file.

  • spring.http.multipart.enabled=trueFile upload is supported by default.
  • spring.http.multipart.file-size-threshold=0# Support file writing to disk.
  • spring.http.multipart.location=# temporary directory for uploading files
  • spring.http.multipart.max-file-size=1Mb# Maximum supported file size
  • spring.http.multipart.max-request-size=10Mb# Maximum request size supported

The last two configurations, most commonly used, limit the upload size of a file and raise an exception if the size is exceeded:

See here for more configuration information: Common Application Properties

5. 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"; }}Copy the code

Set @controllerAdvice to monitor if Multipart uploads are limited in size and alert the front page when this exception occurs. There are a lot of things you can do with @ControllerAdvice, such as universal exception handling, for those of you who are interested.

6, summary

This is a simple Demo that uses Spring Boot to upload files. If you are interested, download the sample code and try it out.

Reference:

Spring Boot file upload example

Example code – Github

Example code – code cloud