application.properties配置:
- 是否开启文件上传
spring.servlet.multipart.enabled= - 文件超过多大时放入缓存中
spring.servlet.multipart.file-size-threshold= - 保存的临时位置
spring.servlet.multipart.location= - 最大的文件大小(单个文件不能超过)
spring.servlet.multipart.max-file-size= - 请求最大的文件大小(可能会上传多个文件)
spring.servlet.multipart.max-request-size= - 是否延迟解析
spring.servlet.multipart.resolve-lazily=
测试代码
前端页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
后端处理请求代码:
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/upload")
String Upload(MultipartFile file, HttpServletRequest req){
//获取临时目录
String realPath = req.getServletContext().getRealPath("/");
//获得路径
String format = sdf.format(new Date());
String path = realPath + format;
//创建文件夹
File fold = new File(path);
while (!fold.exists()){
fold.mkdirs();
}
String oldname = file.getOriginalFilename();
//新文件名
String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."));
try {
file.transferTo(new File(fold,newname));
//生成存储路径
String s = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newname;
return s;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}