Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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);
      return resolver;
    }
  3. In the JSP, set the HTML form encoding to multipart/form-data:

    <form:form method="POST" modelAttribute="defaultUser" enctype="multipart/form-data...