SpringBoot , how can i set MultipartFile size limit base on each controller or requestmapping

Viewed 311

how can I set MultipartFile size limit base on each controller or request mapping

I think this set is a global setting.

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

if I have two endpoints.

1.POST /images <- This path should be limited to 1M

2.POST /videos <- This path should be limited to 50M

how can I limit each endpoint?

1 Answers

You have to declare a Bean of type MultipartResolver

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver
      = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(10485760) 
    return multipartResolver;

Below controller will help you to limit the size. If you exceed the upload size that will provide an 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;
}
Related