用springboot写一个文件上传功能
时间: 2023-07-04 11:14:27 浏览: 86
好的,以下是一个简单的Spring Boot文件上传功能的实现:
1. 首先在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 创建一个文件上传的Controller:
```java
@Controller
public class FileUploadController {
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@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("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/";
}
}
```
3. 创建一个上传页面upload.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>File Upload Example</title>
</head>
<body>
<h1>File Upload Example</h1>
<p th:text="${message}"></p>
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file"/><br/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
```
4. 配置文件上传的相关属性:
```properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
```
以上就是一个简单的Spring Boot文件上传功能的实现,希望能对你有所帮助!
阅读全文