springboot中文件上传代码
时间: 2024-04-30 08:19:52 浏览: 89
在 Spring Boot 中实现文件上传可以使用 Spring MVC 的 MultipartResolver 接口和 MultipartFile 类。
首先在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
```
接着在 Spring Boot 的配置文件中添加以下配置:
```properties
# 文件上传大小限制
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
```
然后在 Controller 中添加以下代码:
```java
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
// 文件为空
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件大小
long fileSize = file.getSize();
// 获取文件类型
String fileType = file.getContentType();
// 获取文件字节流
byte[] fileBytes = file.getBytes();
// 文件保存路径
String filePath = "D:/upload/" + fileName;
// 保存文件
FileUtils.writeByteArrayToFile(new File(filePath), fileBytes);
// 返回上传成功信息
return "上传成功";
}
```
在以上代码中,我们首先判断文件是否为空,然后获取文件的相关信息,包括文件名、文件大小、文件类型和文件字节流。接着将文件保存到指定的路径,并返回上传成功信息。
需要注意的是,这里使用了 FileUtils 类的 writeByteArrayToFile 方法保存文件,需要在 pom.xml 文件中添加 commons-io 依赖。
阅读全文
相关推荐


















