准备HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>user</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/user/upload" method="post" enctype="multipart/form-data">
<label>账号</label><input type="text" name="username"><br/>
<label>照片</label><input type="file" name="upload"><br/>
<input type="submit" value="提交">
</form>
<h1><a href="/user/download">文件下载</a></h1>
</body>
</html>
controller
@RestController
public class UplaodController {
//上传 注意:upload名称要和html input中name相同
@RequestMapping("/user/upload")
public String upload(MultipartFile upload, String username) throws IOException {
System.out.println("username="+username+"----"+"upload="+upload.getOriginalFilename());
upload.transferTo(new File("D:\\",upload.getOriginalFilename()));
return "success";
}
//下载
@RequestMapping("/user/download")
public String download(HttpServletResponse req,HttpServletResponse resp){
File file = new File("D:\\1.webp");
resp.setCharacterEncoding("utf-8");
resp.setContentType("multipart/form-data");
resp.setHeader("Content-Disposition","attachment;filename=1.webp");
FileInputStream in =null;
ServletOutputStream out =null;
try {
in = new FileInputStream(file);
out = resp.getOutputStream();
byte [] b =new byte[1024];
int len =0;
while ((len=in.read(b))!= -1){
out.write(b,0,len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
in.close();
out.close() ;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return "success!!!";
}
}
application.properties添加下面三个选项
spring.servlet.multipart.enabled=true
#设置单个文件总大小
spring.servlet.multipart.max-file-size=20MB
#一次上传文件的总大小
spring.servlet.multipart.max-request-size=20MB