Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Spring MVC Maxupload Size Error

I know its hard to check the file size at the client side(browser) with just pure javascript only.

Now, my question is, Is there a way at the server side to catch an exception such as this?

org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 2000000 bytes

What happens is that, it does not reach my @controller post method and it just throws up the exception that is being catch up by my error.jsp.

What I was thinking is that, is it possible to do this in spring mvc annotated method?

@RequestMapping("/uploadFile.htm")
    public String uploadAttachment(
        HttpServletRequest request,
        @RequestParam(required = false, value = "attached-file") MultipartFile file,
        ModelMap model) throws Exception {

        if(checkfilesize(file)){
            //populate model
            //add error if appplicable
            //return same form again
        }
        //return success
    }       
}

My problem is, it doesnt reaches upto this point and just throw up a big fat exception.

Although the error.jsp was able to catch it, I would think its much user friendly if I can alert the user that the file they are about to upload exceeds the limit.

This is Spring MVC 2.5 app by the way. Is this possible?

like image 719
Mark Estrada Avatar asked Jul 20 '10 06:07

Mark Estrada


2 Answers

This exception is thrown in DispatcherServlet.doDispatch(), so you should be able to catch this using a HandlerExceptionResolver configured in your context.

like image 88
skaffman Avatar answered Oct 20 '22 01:10

skaffman


Alternatively, don't specify maxUploadSize, and check in the controller / validator if the size exceeds your limit:

if (file.getSize() > 2000000) {
    result.rejectValue("file", "<your.message.key>");
}

This checks the size of the file in question, not the file plus all the other request parameters as CommonsMultipartResolver's maxUploadSize does.

like image 32
Markus Pscheidt Avatar answered Oct 19 '22 23:10

Markus Pscheidt