开发者

How to prevent file loaded in memory entirely while checking its size using CommonsMultipartFile ? (java, spring)

I have a form object that is being filled correctly automagically by Spring. Within this form object I have a field:

CommonsMultipartFile file;

The user can upload a file and the form object contains the file properly. All is good. However, I want to make sure a user cannot upload files larger than 2 MB. I have made a check and a开发者_JAVA百科lso that works.

The problem: When I upload a very large file (say 500MB), I will end up with such a large file in memory in my form object (I assume this). Is there any way to prevent this? Like, is there any way to check the file size with a validator, but without the need to load up the entire file before checking?


Assuming that you're using CommonsMultipartResolver, then you can use its maxUploadSize property to limit this. See docs for an example.


In order to catch that MaxUploadSizeExceededException, I use the following :

In the controller, you should implement the HandlerExceptionResolver interface.

Then, implement the resolveException method :

// Catch file too big exception
@Override
public ModelAndView resolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception exception) {
    if (exception instanceof MaxUploadSizeExceededException) {
        // Do something with exception here
    }       

    // Goes back to original view here
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("uploadFile", new UploadFile());
    return new ModelAndView(associatedView,model);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜