springboot controller 上传文件
时间: 2025-01-10 13:39:08 浏览: 43
### Spring Boot Controller 实现文件上传
在构建基于Spring Boot的应用程序时,实现文件上传功能是一项常见任务。为了支持文件上传操作,在`Controller`层需定义相应的接口方法。
#### 定义文件上传接口
创建一个控制器类用于处理文件上传请求:
```java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "Failed to upload empty file";
}
try {
// 处理文件保存逻辑...
byte[] bytes = file.getBytes();
// 假设这里执行实际存储过程
return "Successfully uploaded - " + file.getOriginalFilename();
} catch (Exception e) {
return "Failed to upload " + file.getOriginalFilename() + ": " + e.getMessage();
}
}
}
```
此代码片段展示了如何接收单个文件作为参数,并对其进行基本验证和处理[^2]。
#### 配置文件上传属性
对于较大的文件或多个并发上传的情况,默认配置可能不够用。可以在`application.properties`中调整这些设置以适应具体应用场景的需求:
```properties
# 设置最大文件大小(字节)
spring.servlet.multipart.max-file-size=10MB
# 设置总请求大小限制(字节),适用于多文件上传场景
spring.servlet.multipart.max-request-size=50MB
```
上述配置项允许自定义文件尺寸上限以及整个HTTP POST请求的最大容量[^1]。
阅读全文
相关推荐


















