Spring has built-in multipart support to handle fileuploads in web applications. The design for the multipart support is done with pluggable MultipartResolver objects. This object available on Spring library, defined in the org.springframework.web.multipart.MultipartFile package. Out of the box, Spring provides MultipartResolvers for use with Commons FileUpload (http://jakarta.apache.org/commons/fileupload) and COS FileUpload (http://www.servlets.com/cos). In this post, it shows you how to handle file upload in Spring MVC web application.

By default, no multipart handling will be done by Spring. You will have to enable it yourself by adding a multipart resolver to the web application’s context. After you have done that, each request will be inspected to see if it contains a multipart. If no multipart is found, the request will continue as expected. However, if a multipart is found in the request, the MultipartResolver that has been declared in your context will be used. After that, the multipart attribute in your request will be treated like any other attribute.

Using the MultipartResolver

The CommonsMultipartResolver is a common MultipartResolver implementation, which use the Apache commons upload library to handle the file upload in a form. To use CommonsMultipartResolver to handle the file upload, you need to get the commons-fileupload.jar andcommons-io.jar libraries.

The following example shows how to use the CommonsMultipartResolver:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

This is an example using the CosMultipartResolver:

<bean id="multipartResolver" class="org.springframework.web.multipart.cos.CosMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

Continue reading