WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Advanced · question 60 of 100

How can you handle file uploads in a Spring MVC application?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics