Upload Image With Spring Boot and Thymeleaf – 用Spring Boot和Thymeleaf上传图片

最后修改: 2022年 8月 4日

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.

在这个快速教程中,我们将看看如何使用Spring Boot和Thymeleaf在Java Web应用程序中上传图片

2. Dependencies


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

我们只需要两个依赖项–Spring Boot web和Thymeleaf。


3. Spring Boot Controller

3.Spring Boot控制器

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

我们的第一步是创建一个Spring Boot网络控制器来处理我们的请求。

@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());
        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.

我们已经定义了两个方法来处理HTTP GET请求。displayUploadForm()方法处理GET请求,并返回要显示给用户的Thymeleaf模板的名称,以便让他导入图片。

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.

uploadImage()方法处理图片的上传。它接受图像上传的multipart/form-data POST请求,并将图像保存在本地文件系统中。MultipartFile接口是Spring Boot提供的一种特殊数据结构,用于表示多部分请求中的上传文件

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:


<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">
                    <button type="submit" class="btn btn-primary">Upload image</button>
                <span th:if="${msg != null}" th:text="${msg}"></span>

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.

在这篇快速文章中,我们介绍了如何在一个基于Spring Boot和Thymeleaf的Java网络应用中上传图片。

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