<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<br>
<button>上传</button>
</form>
<img src="/avatar/1.png">
</body>
@PostMapping("/upload")
@ResponseBody
public String singFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败";
} else {
String path = String.format("%s/%s", uploadDir, file.getOriginalFilename());
try(FileOutputStream os = new FileOutputStream(path)) {
byte fileContent[] = file.getBytes();
os.write(fileContent);;
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
}
注:
上传的文件一般放在项目代码外,不放在static中
路径加/不加/:不加:相对路径,服务器可能找不到