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:

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

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

public String handleFileUpload(@RequestParam("myFile") MultipartFile file)
    if (!file.isEmpty())
        String name = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            Files.write(new File(name).toPath(), bytes);
        catch (Exception e)
    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/ file, and add the following configuration into it:


Enjoy uploading Files with Spring Boot!

FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials
Cookie Policy

Cookie Policy This website uses cookies that are necessary to its functioning and required to achieve the purposes illustrated in the privacy policy. By accepting this OR scrolling this page OR continuing to browse, you agree to our privacy policy.

© 2020 Your Company. All Rights Reserved. Designed By JoomShaper

Please publish modules in offcanvas position.