Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we'll take a look at how to upload an image in a Java web application using Spring Boot and Thymeleaf.

2. Dependencies

We'll only need two dependencies — Spring Boot web and Thymeleaf:

<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>

3. Spring Boot Controller

Our first step is to create a Spring Boot web controller to handle our requests:

@Controller public class UploadController {

    public static String UPLOAD_DIRECTORY = System.getProperty("user.dir") + "/uploads";

    @GetMapping("/uploadimage") public String displayUploadForm() {
        return "imageupload/index";
    }

    @PostMapping("/upload") public String uploadImage(Model model, @RequestParam("image") MultipartFile file) throws IOException {
        StringBuilder fileNames = new StringBuilder();
        Path fileNameAndPath = Paths.get(UPLOAD_DIRECTORY, file.getOriginalFilename());
        fileNames.append(file.getOriginalFilename());
        Files.write(fileNameAndPath, file.getBytes());
        model.addAttribute("msg", "Uploaded images: " + fileNames.toString());
        return "imageupload/index";
    }
}

We've defined two methods to handle HTTP GET requests. The displayUploadForm() method handles the GET request and returns the name of the Thymeleaf template to display to the user in order to let him import an image.

The uploadImage() method handles the image upload. It accepts a multipart/form-data POST request on image upload and saves the image on the local file system. The MultipartFile interface is a special data structure that Spring Boot provides to represent an uploaded file in a multipart request.

Finally, we created an upload folder that will store all the uploaded images. We also added a message, containing the name of the uploaded image, to display after the user submits the form.

4. Thymeleaf Template

The second step is to create a Thymeleaf template that we'll call index.html in the path src/main/resources/templates. This template displays an HTML form to allow the user to select and upload an image. Furthermore, we use the accept=”image/*” attribute to allow users to import images only instead of importing any kind of files.

Let's see the structure of our index.html file:

<body>
<section class="my-5">
    <div class="container">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <h2>Upload Image Example</h2>
                <p th:text="${message}" th:if="${message ne null}" class="alert alert-primary"></p>
                <form method="post" th:action="@{/upload}" enctype="multipart/form-data">
                    <div class="form-group">
                        <input type="file" name="image" accept="image/*" class="form-control-file">
                    </div>
                    <button type="submit" class="btn btn-primary">Upload image</button>
                </form>
                <span th:if="${msg != null}" th:text="${msg}"></span>
            </div>
        </div>
    </div>
</section>
</body>

5. Custom File Size

If we try to upload a large file, a MaxUploadSizeExceededException exception will be thrown. However, we can tune the file upload limits through the properties spring.servlet.multipart.max-file-size and spring.servlet.multipart.max-request-size that we define in the application.properties file:

spring.servlet.multipart.max-file-size = 5MB
spring.servlet.multipart.max-request-size = 5MB

6. Conclusion

In this quick article, we presented how to upload an image in a Java web application based on Spring Boot and Thymeleaf.

As always, the complete source code for this article can be found over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments