<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Index</title>
</head>
<body>
<form action="/load" method="post" enctype="multipart/form-data">
<input type="file" name="file2"><br>
<input type="submit" value="文件上传">
</form>
</body>
</html>
@Controller
public class HelloController {
@PostMapping("/load")
@ResponseBody
// 当 <input type="file" name="file2"> 的 name 不是 file 的时候,需要 @RequestAttribute
public String load(@RequestAttribute("file2") MultipartFile file) {
if (file != null && !file.isEmpty()) {
try {
File f = new File("E:/", Objects.requireNonNull(file.getOriginalFilename()));
file.transferTo(f);
return "ok";
} catch (Exception e) {
return "error";
}
}
return "error";
}
}
- 可以不使用
MultipartFile
,直接通过 HttpServletRequest
获取 getPart
(getParts()
) 来自己实现,但没必要