How to upload files in Spring Boot web applications

HTML pages can configure files to be uploaded using as enctype attribute “multipart/form-data“. Out of the box, the org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration already has support to enable multi-part upload. So let’s see an example HTML page with a form with enctype=”multipart/form-data” to upload a file:

<?xml version="1.0"?>
<form action="uploadFile" th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">
  <input type="file" name="myFile"/>
  <input type="submit"/>
</form>

In order to handle the request, we can implement a Controller as shown in this example:

  @PostMapping("/uploadFile")
  public String handleFileUpload(@RequestParam("myFile") MultipartFile file) {
    if (!file.isEmpty()) {
      String name = file.getOriginalFilename();
      try {
        byte[] bytes = file.getBytes();
        Files.write(new File(name).toPath(), bytes);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return "redirect:/fileUpload";
  }

Finally, we need to configure our Spring Boot application to enable Multipart file uploads, and set the maximum file size that can be uploaded. Open src/main/resources/application.properties file, and add the following configuration into it:

spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=2MB spring.servlet.multipart.max-request-size=20MB spring.servlet.multipart.file-size-threshold=5MB 

Enjoy uploading Files with Spring Boot!

Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon