如何根据每个控制器或requestmapping设置MultipartFile大小限制
我认为此设置是全局设置。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
如果我有两个端点。
1.POST / images <- 此路径应限制为1M
2.POST /视频<- 此路径应限制为50M
我如何限制每个末端突突?
答案 0 :(得分:3)
您必须声明MultipartResolver类型的Bean
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver
= new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10485760)
return multipartResolver;
下面的控制器将帮助您限制大小。如果超出上传大小,则将提供MaxUploadSizeExceededException
@RequestMapping(value = "/images", method = RequestMethod.POST)
public ModelAndView uploadFile(MultipartFile file) throws IOException {
ModelAndView modelAndView = new ModelAndView("file");
InputStream in = file.getInputStream();
File currDir = new File(".");
String path = currDir.getAbsolutePath();
FileOutputStream f = new FileOutputStream(
path.substring(0, path.length()-1)+ file.getOriginalFilename());
int ch = 0;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
modelAndView.getModel().put("message", "File has uploaded" );
return modelAndView;
}