Close

Create File Upload Servlet using @MultipartConfig

[Last Updated: Nov 4, 2018]

@MultipartConfig annotation is used to define a servlet, handling mime type multipart/form-data to upload a file from client to server.

The HttpServletRequest object of the corresponding servlet is responsible to make the mime attachments available via the getParts and getPart methods to iterate over the various mime attachments.

Let's consider following web.xml file upload configuration.

<servlet>
    <servlet-name>fileUploadController</servlet-name>
    <servlet-class>com.logicbig.upload.FileUploadController</servlet-class>
    <multipart-config>
        <max-file-size>104448</max-file-size>
        <max-request-size>26214400</max-request-size>
        <file-size-threshold>1048576</file-size-threshold>
    </multipart-config>
</servlet>
<servlet-mapping>
    <servlet-name>fileUploadController</servlet-name>
    <url-pattern>/upload/*</url-pattern>
</servlet-mapping>

We are going to create equivalent annotation based servlet.

  1. Prepare project
    • Create web application using maven-archetype-webapp, steps here.
    • Delete web.xml, we don't need it at all.
    • In pom.xml add dependency of javax.servlet-api:3.0.1
    • In pom.xml add tomcat7-maven-plugin to run it as embedded server.
    • Modify index.jsp under webapp folder, create a form to send multipart/form-data post request
  2. Create a servlet class FileUploadController annotated with @WebServlet and @MultipartConfig
  3. Make sure the folder specified by location exists.
  4. Now we are going to run our web application from root folder:
    mvn clean tomcat7:run-war
  5. Put following url in your browser:
    http://localhost:8080/file-upload-example/
    You should see the upload file form. Choose the file in the form and click on 'upload File' button. File should be created at 'd:\tmp' location.

Example Project

Dependencies and Technologies Used:

  • Java Servlet API 3.0.1
  • JDK 1.8
  • Maven 3.0.4

Servlet File Upload Example Select All Download
  • web-file-upload-servlet
    • src
      • main
        • java
          • FileUploadController.java
          • webapp

    See Also