利用springboot实现文件上传
时间: 2023-11-02 21:18:15 浏览: 40
好的,我可以为您提供一些实现文件上传的代码示例。
首先,您需要在您的pom.xml文件中添加以下依赖项:
```
<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>
```
然后,您可以创建一个控制器类来处理文件上传请求。以下是一个基本示例:
```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:uploadStatus";
}
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:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}
```
在此示例中,我们使用了Thymeleaf模板引擎来呈现上传表单和上传状态页面。以下是一个基本的上传表单:
```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>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
```
最后,我们需要创建一个上传状态页面来显示上传结果。以下是一个基本的上传状态页面:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Upload Status</title>
</head>
<body>
<h1>Upload Status</h1>
<p th:text="${message}"></p>
<br/><br/>
<a href="/">Upload another file</a>
</body>
</html>
```
希望这个示例可以帮助您实现文件上传功能。