Spring MVC File Upload Validation Example

This tutorial shows you about Spring MVC File Upload Validation Example. This example uses Spring validator to validate the uploaded file. When the file is empty or exceeds the maximum allowed upload size, the exception is caught and response a appropriate message.

If you don’t know about Spring MVC yet, firstly you should refer to the post Spring MVC Annotation Example

Other interesting posts you may like

Table of contents:
1. Maven Dependencies
2. Project Structure
3. Spring MVC File Upload Java/XML Configuration
4. Spring MVC File Upload
5. Spring MVC File Upload Exception Handling
6. Upload file views
7. Deploy Spring MVC File Upload Validation Example

Now, we are ready to build the Spring MVC File Upload Validation Example step by step

Maven Dependencies
We added the commons-fileupload which is used to upload a MultipartFile. We also include the javax.validation API so we can annotate our controller methods with the @Valid annotation.

Project Structure
The Project structure will looks like the following structure.

Spring MVC File Upload Validation Example project

Spring MVC File Upload Java/XML Configuration
The CommonsMultipartResolver saves temporary files to the temporary directory in application server. The following properties should be configured for the file upload operation: maxUploadSize, maxUploadSizePerFile, maxInMemorySize, uploadDir, defaultEncoding and resolveLazily. Although they are optionally but you need to set the property resolveLazily to true if you want to catch execption correctly.

If you want to adapt the file upload feature into your current Spring MVC XML configuration. You can add the below configuration. It is equivalent with the above java configuration.

For simplicity, the navigation cases will be put in a NavigationController.

Validation Messages
These validation messages are used to display an appropriate message with an error operation to the user. These messags are stored in the property file messages.properties that is located in the src/main/resources/ folder.

Spring MVC File Upload
The FileModel has a MultipartFile object which will hold the uploaded file.

Next, you have to define the FileUploadController that is responsible for uploading a file.

Let’s dig deeper

The FileUploadController will upload a file to a /tmp/ directory. We bind the FileValidator onto the controller by using the @InitBinder annotation and provide a WebDataBinder as an argument in the initBinderFileModel method.
Finally, we create the handleFormUpload method to handle the file upload. By annotating the FileModel with the @Valid annotation, the binded validators are automatically executed on form submission. The RedirectAttributes is used to forward the response to a success page and the BindingResult is used to redirect to the current page if any errors have occurred.

If the file is empty, we will provide an appropriate error message by using the validator such as below

Spring MVC File Upload Exception Handling
You need to add a global exception handler to catch the MultipartException because it is thrown before reaching the controller. This exception handler is registered with container by using the @ControllerAdvice annotation. The methods are annotated with the @ExceptionHandler annotation to handle specific exceptions. The implementation of methods are detailed such as the below code snippet.

Upload file views
We created a simple view to upload a file.

Upload view

Success View

When the file is successfully uploaded, the file name will displayed

Error View

The content of the error is displayed if an error occurs.

Deploy Spring MVC File Upload Validation Example
Building project with maven then deploy file war on application server or servlet container (Tomcat 8 for example). Access the address URL http://localhost:8080/spring-mvc-file-upload/ and browse a file to upload such as the below screen shot.

Spring MVC File Upload Validation Example screenshot

Click the Upload button the success screen will display

Spring MVC File Upload Validation Example screensucces

Click the Upload Page link to return the Upload form screen and browse other file that its size exceeds 10 Kb. The error screen will display such as

Spring MVC File Upload Validation Example screenerror

That’s it on how to build Spring MVC File Upload Validation Example. The next tutorial will show you about Spring MVC Multiple File Upload Validation Example

Download complete source code of example, please click link below

Spring-MVC-File-Upload-Validation-Example.zip (65 downloads)

Source code on Github https://github.com/javabycode/spring-mvc-file-upload-validation-example

Leave a Comment

*

Please share it if you found this useful
Hide Buttons