springBoot 图片上传及回显的代码实现
时间: 2024-05-05 15:16:04 浏览: 90
以下是一个基于Spring Boot的图片上传及回显的代码实现示例,其中使用了Thymeleaf模板引擎:
1. 配置文件中添加文件上传配置:
```yaml
spring:
servlet:
multipart:
max-file-size: 10MB # 文件大小限制
max-request-size: 10MB # 请求大小限制
file-size-threshold: 2KB # 临时文件大小限制
```
2. 控制器中添加上传及回显的方法:
```java
@Controller
public class ImageController {
// 上传图片页面
@GetMapping("/upload")
public String uploadPage(Model model) {
model.addAttribute("image", new Image());
return "upload";
}
// 上传图片并回显
@PostMapping("/upload")
public String uploadImage(@ModelAttribute("image") Image image, BindingResult result) throws IOException {
if (result.hasErrors()) {
return "upload";
}
// 保存图片到本地文件系统
byte[] bytes = image.getFile().getBytes();
Path path = Paths.get("images/" + image.getFile().getOriginalFilename());
Files.write(path, bytes);
// 设置图片URL
image.setUrl("/images/" + image.getFile().getOriginalFilename());
return "redirect:/upload";
}
}
```
3. 在Thymeleaf模板中添加上传表单及回显图片:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Image Upload</title>
</head>
<body>
<h1>Image Upload</h1>
<!-- 上传表单 -->
<form action="#" th:action="@{/upload}" th:object="${image}" method="post" enctype="multipart/form-data">
<div>
<label for="file">Choose an image:</label>
<input type="file" id="file" name="file" accept="image/*" required="required" th:field="*{file}" />
</div>
<div>
<button type="submit">Upload</button>
</div>
</form>
<!-- 回显图片 -->
<div th:if="${image.url != null}">
<img th:src="@{${image.url}}" alt="Uploaded image" />
</div>
</body>
</html>
```
其中,Image类用于封装上传的文件和回显的图片URL:
```java
public class Image {
private MultipartFile file;
private String url;
// getters and setters
}
```
阅读全文