Uploading a file

To allow a user to upload a file from an HTML form, we need to set the form encoding to multipart/form-data. On the server side, we will use the fileupload package from the Apache Commons library to process the uploaded file.

How to do it…

Here are the steps to upload a file from a form:

  1. Add the Maven dependency for fileupload from Apache Commons in pom.xml:
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  2. In the Spring configuration, declare a MultipartResolver bean with a size limit (in bytes) for the data to be uploaded:
    @Bean MultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(500000000); ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.