如何基于每个控制器或请求映射设置MultipartFile大小限制
我认为这是全球背景。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
如果我有两个端点。
1.POST /图片此路径应限制为1M
2.POST /视频此路径应限制为50M
如何限制每个端点?
最佳答案
您必须声明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;
}