表单方式
<!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";
}
}
官网使用的是 @RequestPart
注解,这里也推荐这种方式
public class HelloController {
@PostMapping("/load")
@ResponseBody
public String load(@RequestPart("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";
}
}
axios 方式
<!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>
<script src="/webjars/axios/0.21.1/dist/axios.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<input type="button" value="上传" id="btn">
<script>
let btn = document.getElementById("btn");
btn.onclick = function () {
// 获取 FileList
let files = document.getElementById("file").files;
// 构建表单
let formData = new FormData();
formData.append("file", files[0]);
// 添加其他属性
formData.append("name", "tom");
axios({
method: 'post',
url: '/hello',
// 设置头文件
headers: {
'Content-Type': 'multipart/form-data'
},
data: formData
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
};
</script>
</body>
</html>
@RestController
public class HelloController {
@PostMapping(value = {"/", "/hello"})
public String hello(MultipartFile file, String name) {
if (file != null && !file.isEmpty()) {
System.out.println("name: " + name);
return file.getOriginalFilename();
}
return "hello world";
}
}
- 可以不使用
MultipartFile
,直接通过HttpServletRequest
获取getPart
(getParts()
) 来自己实现,但没必要