Spring Boot file upload 

  28 June 2020

  Ahmed Nafisul Bari

Spring Boot file upload cover image

Uploading files and images via Spring Boot to local storage is an easy process but there are many ways to do so. Here, I show you the most simple and easy method to upload files and images to your local storage with spring boot and FreeMarker template engine in 3 steps.

Step 1

Create a ‘local-storage’ folder in the root directory of your project.

spring boot image file upload

Step 2

Create an HTML form to select the file to upload.

<h1>SpringBoot file upload example</h1>

<#--if the flag has a message it will show-->
<#if flag??>
    <h2 style="color: #a39146">${flag}</h2>
</#if>

<form action="/upload-action" enctype="multipart/form-data" method="post">
    <label>Please select a file</label><br><br>
    <input type="file" name="myfile"><br><br>
    <input type="submit" value="Submit">
</form>

A FreeMarker ‘if’ syntax is present here with a flag variable to prompt success or failed message.

Step 3

Now, we need to create a method to do the upload operation. In the controller class, the uploadAction method is doing so. Here, we are selecting the ‘local-storage’ folder that we created in step 1 to save the file in. With java.nio.file.Files’s copy method the actual saving of the file is done.

@Controller
public class UploadController {


    @GetMapping("/")
    public ModelAndView index() {
        return new ModelAndView("index");
    }


    @PostMapping("/upload-action")
    public ModelAndView uploadAction(@RequestParam("myfile") MultipartFile theFile, Model model) {

        //selecting the local-storage folder to save the files
        String uploadDir = System.getProperty("user.dir") + "\\local-storage\\";

        String fileName = theFile.getOriginalFilename();

        try {
            //saving the file to the selected folder
            Files.copy(theFile.getInputStream(), Paths.get(uploadDir + fileName), StandardCopyOption.REPLACE_EXISTING);

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

            //a friendly flag if the uploading fails
            model.addAttribute("flag", "Upload Failed");
            return new ModelAndView("index");
        }

        model.addAttribute("flag", "Upload Successful, Check the 'local-storage' folder");
        return new ModelAndView("index");
    }
}

When the code catches an exception it is simply returning a flag message of upload failed. If the upload operation is successful, the flag is showing a success message.

Bonus

In the application.properties file, you can set the max file upload size limit and have more control over your spring boot server.

spring.servlet.multipart.max-file-size=512KB

This project can be found at this GitHub repository