springboot上传文件
时间: 2023-06-19 10:36:09 浏览: 111
在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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
```
2. 在`application.properties`文件中添加以下配置:
```properties
# 文件上传大小限制
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
# 文件上传保存路径
file.upload.path=/path/to/upload
```
3. 创建上传文件的HTML表单(使用Thymeleaf模板引擎)
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
```
4. 创建文件上传的Controller
```java
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class UploadController {
@Value("${file.upload.path}")
private String uploadPath;
@RequestMapping("/upload")
public String upload() {
return "upload";
}
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("msg", "Please select a file to upload");
return "upload";
}
try {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
File destFile = new File(uploadPath + "/" + fileName);
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
model.addAttribute("msg", "File uploaded successfully");
} catch (IOException e) {
model.addAttribute("msg", "File upload failed : " + e.getMessage());
}
return "upload";
}
}
```
在上述代码中,`@Value`注解用于获取`application.properties`文件中的`file.upload.path`配置项的值,`@RequestMapping`注解用于返回上传文件的HTML表单,`@PostMapping`注解用于处理文件上传的请求,`@RequestParam`注解用于获取上传的文件,`FileUtils.copyInputStreamToFile()`方法用于将上传的文件保存到指定路径。
5. 运行Spring Boot应用程序并访问上传文件的HTML表单页面,选择一个文件并点击“Upload”按钮,上传文件成功后会显示“File uploaded successfully”消息。
阅读全文