MultipartFile的用法
时间: 2023-12-09 16:36:43 浏览: 52
MultipartFile是Spring框架中的一个接口,用于处理HTTP请求中的文件上传。以下是MultipartFile的用法示例:
1. 单文件上传
```java
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName = file.getOriginalFilename();
String filePath = "D:/upload/";
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
return "上传失败!";
}
}
```
2. 多文件上传
```java
@PostMapping("/batch/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile[] files) {
StringBuilder sb = new StringBuilder();
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue;
}
String fileName = file.getOriginalFilename();
String filePath = "D:/upload/";
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
sb.append(fileName).append("上传成功;");
} catch (IOException e) {
sb.append(fileName).append("上传失败;");
}
}
return sb.toString();
}
```
阅读全文