Spring MVC File Upload Max Size Validation

In one of the earlier posts we have seen Spring MVC File Upload Example. What happens if you have a specific requirement of not allowing users to upload file of over a specified limit? In simple apps, you may end up getting the file size and then may be throwing an exception if file size goes above limit. Things are easier in Spring. We have a property that helps define you a limit of max size for file upload.

Lets see an example of Spring MVC File Upload Max Size Validation

1. Dispatcher Servlet Configuration for Max upload property

In the CommonsMultipartResolver bean we add a property maxUploadSize and specify the maximum allowed limit in bytes.

2. Controller for File Upload

3. Exception Handler for Max Upload exception

We will add a Exception handler that will catch the MultipartException when a File above limits is uploaded. In the handleFileUploadException method you can add your own implementation on how you want to handle the exception. I have added the exception message to a Model and displayed it on the Error page.

4. Output

Spring MVC Tutorial | Spring MVC File Upload Max Size Validation

Spring MVC File Upload Max Size Validation | Spring MVC Tutorial

Download Full Code – SpringMVCFileUploadMaxSize.zip

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn