Java Spring MVC provides built-in mechanisms for handling file uploads that allow users to upload files to web applications. Spring MVC has a multipart resolver that is used to handle file uploads.
Here are the steps to handle file uploads in a Spring MVC application:
1. Add the following dependencies to your Maven or Gradle build file:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>{spring-version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>{commons-fileupload-version}</version>
</dependency>
2. Configure the multipart resolver in your Spring configuration file:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>
The maxUploadSize property is used to set the maximum upload file size in bytes.
3. Create a controller method to handle file uploads:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
// logic to handle file upload
return "uploadSuccess";
}
In this example, the @RequestParam annotation is used to bind the uploaded file to a MultipartFile object.
4. Create a HTML form to upload files:
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file"/><br/><br/>
<input type="submit" value="Upload"/>
</form>
The enctype attribute is set to "multipart/form-data" to enable file uploads.
That’s it! With these steps, you can handle file uploads in Spring MVC.