用springboot写个上传图片的功能
时间: 2024-06-11 21:04:29 浏览: 62
以下是使用Spring Boot实现上传图片的示例代码:
1.首先,在pom.xml文件中添加以下依赖项:
```xml
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Boot DevTools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
```
2.在application.properties文件中添加以下配置:
```properties
# 配置上传文件的存储路径
spring.servlet.multipart.location=upload-dir
# 配置上传文件的最大大小
spring.servlet.multipart.max-file-size=10MB
# 配置请求的最大大小
spring.servlet.multipart.max-request-size=10MB
```
3.创建一个UploadController类,其中包含一个用于处理文件上传请求的POST方法:
```java
@Controller
public class UploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get("upload-dir/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/";
}
}
```
4.创建一个HTML表单,允许用户选择要上传的文件:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<div>
<input type="file" name="file"/>
</div>
<button type="submit">Upload</button>
</form>
<p th:text="${message}"></p>
</body>
</html>
```
5.运行应用程序并访问http://localhost:8080/,选择要上传的文件并单击“上传”按钮。上传后,您应该会看到一个成功上传消息。您可以在“upload-dir”文件夹中找到已上传的文件。
希望这个示例可以帮助您实现上传图片的功能。
阅读全文