Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!