拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用Spring Boot 和Thymeleaf 上传图像

使用Spring Boot 和Thymeleaf 上传图像

白鹭 - 2022-08-08 2179 0 2

一、概述

在本快速教程中,我们将了解如何使用Spring Boot 和Thymeleaf 在Java Web 应用程序中上传图像

2. 依赖

我们只需要两个依赖项——Spring Boot web 和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 控制器

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

@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";
}
}

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

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

最后,我们创建了一个上传文件夹来存储所有上传的图片。我们还添加了一条消息,其中包含上传图像的名称,以在用户提交表单后显示。

4.百里香模板

第二步是创建一个Thymeleaf 模板,我们将在路径src/main/resources/templates中调用index.html。此模板显示一个HTML 表单以允许用户选择和上传图像。此外,我们使用accept=”image/*”属性来允许用户只导入图像而不是导入任何类型的文件。

让我们看看我们的index.html文件的结构:

<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 .自定义文件大小

如果我们尝试上传大文件,则会抛出MaxUploadSizeExceededException异常。但是,我们可以通过我们在application.properties文件中定义的属性spring.servlet.multipart.max-file-sizespring.servlet.multipart.max-request-size来调整文件上传限制

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

6 .结论

在这篇快速文章中,我们介绍了如何在基于Spring Boot 和Thymeleaf 的Java Web 应用程序中上传图像。


标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *