Spring Boot (XVII): Use Spring Boot upload files

 

 

Upload files is often one of the Internet application scenarios, the most typical situation is upload an avatar and so on, with everyone doing today took a Spring Boot upload a small case.

1, pom package configuration

We use Spring Boot version 2.1.0, jdk 1.8, tomcat 8.0.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.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>

 

Introduced spring-boot-starter-thymeleafto make the page template engine, write some simple upload examples.

2, disposed startup class

@SpringBootApplication
public class FileUploadWebApplication {

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

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

}

 

tomcatEmbedded code to solve, upload files larger than 10M connection reset problems. This exception also capture content GlobalException not.

Details Reference: Tomcat Large File the Upload the RESET Connection

3, write the front page

Upload page

<!DOCTYPE html>
<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>

 

Post a very simple request, a file selection box to select a submit button, the effect is as follows:

Upload the results display page:

<!DOCTYPE html>
<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>

 

The effect is as follows:

4, the preparation upload control class

Access localhost automatically jump to the upload page:

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

 

Upload business processes

@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";
}

 

The above code means that, by MultipartFilereading the file information, if the file is empty jumps to the results page and prompt; if you do not stream and written to the specified directory, the final results will show an empty page to read the file.

MultipartFileIs a wrapper class Spring uploaded file, and contains information binary stream file attributes file may configure relevant attributes in the configuration file, the basic configuration information as follows:

  • spring.http.multipart.enabled=true # Default support file uploads.
  • spring.http.multipart.file-size-threshold=0 # Support files written to disk.
  • spring.http.multipart.location=# Temporary directory to upload files
  • spring.http.multipart.max-file-size=1Mb # Maximum supported file size
  • spring.http.multipart.max-request-size=10Mb # Maximum support request size

The most commonly used are the last two configuration content, file upload size limit, exceeds the size will throw an exception when uploading:

More configuration information reference herein: the Common Properties file application

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";
    }
}

 

A set @ControllerAdvicefor monitoring the Multipartupload file size is limited, this occurs when abnormal prompt the front page. Use @ControllerAdvicecan do a lot of things, such as global unified exception handling, interested students can understand down.

6, summed up

Such a simple Demo using Spring Boot upload is complete, interested students can download the sample code to try it.

Article content has been upgraded to Spring Boot 2.x

Sample Code -github

Sample code - Code Cloud

reference:

Spring Boot file upload example

 

Article comes from; https://www.cnblogs.com/ityouknow/p/8298344.html

Upload files is often one of the Internet application scenarios, the most typical situation is upload an avatar and so on, with everyone doing today took a Spring Boot upload a small case.

1, pom package configuration

We use Spring Boot version 2.1.0, jdk 1.8, tomcat 8.0.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.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>

 

Introduced spring-boot-starter-thymeleafto make the page template engine, write some simple upload examples.

2, disposed startup class

@SpringBootApplication
public class FileUploadWebApplication {

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

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

}

 

tomcatEmbedded code to solve, upload files larger than 10M connection reset problems. This exception also capture content GlobalException not.

Details Reference: Tomcat Large File the Upload the RESET Connection

3, write the front page

Upload page

<!DOCTYPE html>
<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>

 

Post a very simple request, a file selection box to select a submit button, the effect is as follows:

Upload the results display page:

<!DOCTYPE html>
<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>

 

The effect is as follows:

4, the preparation upload control class

Access localhost automatically jump to the upload page:

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

 

Upload business processes

@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";
}

 

The above code means that, by MultipartFilereading the file information, if the file is empty jumps to the results page and prompt; if you do not stream and written to the specified directory, the final results will show an empty page to read the file.

MultipartFileIs a wrapper class Spring uploaded file, and contains information binary stream file attributes file may configure relevant attributes in the configuration file, the basic configuration information as follows:

  • spring.http.multipart.enabled=true # Default support file uploads.
  • spring.http.multipart.file-size-threshold=0 # Support files written to disk.
  • spring.http.multipart.location=# Temporary directory to upload files
  • spring.http.multipart.max-file-size=1Mb # Maximum supported file size
  • spring.http.multipart.max-request-size=10Mb # Maximum support request size

The most commonly used are the last two configuration content, file upload size limit, exceeds the size will throw an exception when uploading:

More configuration information reference herein: the Common Properties file application

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";
    }
}

 

A set @ControllerAdvicefor monitoring the Multipartupload file size is limited, this occurs when abnormal prompt the front page. Use @ControllerAdvicecan do a lot of things, such as global unified exception handling, interested students can understand down.

6, summed up

Such a simple Demo using Spring Boot upload is complete, interested students can download the sample code to try it.

Article content has been upgraded to Spring Boot 2.x

Sample Code -github

Sample code - Code Cloud

reference:

Spring Boot file upload example

 

Article comes from; https://www.cnblogs.com/ityouknow/p/8298344.html

Guess you like

Origin www.cnblogs.com/JonaLin/p/11411696.html