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.
Here are the steps to upload a file from a form:
Add the Maven dependency for
fileupload
from Apache Commons inpom.xml
:<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
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; }
In the JSP, set the HTML form encoding to
multipart/form-data
:<form:form method="POST" modelAttribute="defaultUser" enctype="multipart/form-data...