This example shows how to upload a file by using CommonsMultipartResolver. Also check out last tutorial to understand how MultipartResolver works.
CommonsMultipartResolver was deprecated in Spring Framework 5.0 and completely removed starting with Spring Framework 6. This example is preserved for legacy projects.
Example
Creating JSP Form
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<h3> Upload File Form <h3>
<br/>
<form action="upload" enctype="multipart/form-data" method="post" >
Upload File: <INPUT type="file" name="user-file">
<INPUT type="submit" value="Upload File">
</form>
</body>
</html>
The attribute enctype must be set to multipart/form-data for file uploading.
The above code will be rendered as:
Creating Controller
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
@RequestMapping("/upload")
public class FileUploadController {
@RequestMapping(method = RequestMethod.GET)
public String handleGet() {
return "file-upload";
}
@RequestMapping(method = RequestMethod.POST)
public String handlePost(@RequestParam("user-file")
MultipartFile multipartFile,
Model model) throws IOException {
String name = multipartFile.getOriginalFilename();
Path path = Paths.get("d:\\filesUploaded\\" + name);
Path parent = path.getParent();
if (!Files.exists(parent)) {
Files.createDirectory(parent);
} else if (Files.exists(path)) {
Files.delete(path);
}
BufferedWriter w = Files.newBufferedWriter(path);
w.write(new String(multipartFile.getBytes()));
w.flush();
model.addAttribute("msg", "File has been uploaded. name: " + name+
" content: "+new String(multipartFile.getBytes()));
return "response";
}
}
In the above example, we are saving the file content in a folder d:\filesUploaded\.
Java Config
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver =
new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver =
new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(20000000);
commonsMultipartResolver.setResolveLazily(false);
return commonsMultipartResolver;
}
}
We also have to add commons-fileupload maven dependency in order for above resolver to work.
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
Output
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Access the file upload form at 'http://localhost:8080/spring-file-upload/upload'.
On submitting the form the user selected file will be created at the location 'd:\\filesUploaded\\'.
Integration Test
package com.logicbig.example;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class UploadControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testController() throws Exception {
MockMultipartFile mockFile = new MockMultipartFile(
"user-file", "test.txt",
null, "test data".getBytes());
this.mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/upload")
.file(mockFile))
.andExpect(status().isOk())
.andExpect(model().attribute(
"msg",
"File has been uploaded. "
+ "name: test.txt "
+ "content: test data"));
}
}
mvn clean test -Dtest="UploadControllerTest" Output$ mvn clean test -Dtest="UploadControllerTest" [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for com.logicbig.example:spring-file-upload:war:1.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-war-plugin is missing. @ line 47, column 21 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] --------------< com.logicbig.example:spring-file-upload >--------------- [INFO] Building spring-file-upload 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- clean:3.2.0:clean (default-clean) @ spring-file-upload --- [INFO] Deleting D:\example-projects\spring-mvc\file-upload\spring-file-upload\target [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-file-upload --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\file-upload\spring-file-upload\src\main\resources [INFO] [INFO] --- compiler:3.5.1:compile (default-compile) @ spring-file-upload --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 3 source files to D:\example-projects\spring-mvc\file-upload\spring-file-upload\target\classes [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-file-upload --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\file-upload\spring-file-upload\src\test\resources [INFO] [INFO] --- compiler:3.5.1:testCompile (default-testCompile) @ spring-file-upload --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to D:\example-projects\spring-mvc\file-upload\spring-file-upload\target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-file-upload --- [INFO] Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.UploadControllerTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.806 s -- in com.logicbig.example.UploadControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 11.743 s [INFO] Finished at: 2026-06-02T17:08:34+08:00 [INFO] ------------------------------------------------------------------------
Using MultipartHttpServletRequest
Instead of using MultipartFile as the handler method parameter, we can alternatively use org.springframework.web.multipart.MultipartHttpServletRequest. Complete example here
Dependencies and Technologies Used: - spring-webmvc 4.3.30.RELEASE (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 4.3.30.RELEASE Version compatibilities of spring-webmvc with this example: javax.servlet-api:3.x
- 3.2.9.RELEASE
- 3.2.10.RELEASE
- 3.2.11.RELEASE
- 3.2.12.RELEASE
- 3.2.13.RELEASE
- 3.2.14.RELEASE
- 3.2.15.RELEASE
- 3.2.16.RELEASE
- 3.2.17.RELEASE
- 3.2.18.RELEASE
- 4.0.0.RELEASE
- 4.0.1.RELEASE
- 4.0.2.RELEASE
- 4.0.3.RELEASE
- 4.0.4.RELEASE
- 4.0.5.RELEASE
- 4.0.6.RELEASE
- 4.0.7.RELEASE
- 4.0.8.RELEASE
- 4.0.9.RELEASE
- 4.1.0.RELEASE
- 4.1.1.RELEASE
- 4.1.2.RELEASE
- 4.1.3.RELEASE
- 4.1.4.RELEASE
- 4.1.5.RELEASE
- 4.1.6.RELEASE
- 4.1.7.RELEASE
- 4.1.8.RELEASE
- 4.1.9.RELEASE
- 4.2.0.RELEASE
- 4.2.1.RELEASE
- 4.2.2.RELEASE
- 4.2.3.RELEASE
- 4.2.4.RELEASE
- 4.2.5.RELEASE
- 4.2.6.RELEASE
- 4.2.7.RELEASE
- 4.2.8.RELEASE
- 4.2.9.RELEASE
- 4.3.0.RELEASE
- 4.3.1.RELEASE
- 4.3.2.RELEASE
- 4.3.3.RELEASE
- 4.3.4.RELEASE
- 4.3.5.RELEASE
- 4.3.6.RELEASE
- 4.3.7.RELEASE
- 4.3.8.RELEASE
- 4.3.9.RELEASE
- 4.3.10.RELEASE
- 4.3.11.RELEASE
- 4.3.12.RELEASE
- 4.3.13.RELEASE
- 4.3.14.RELEASE
- 4.3.15.RELEASE
- 4.3.16.RELEASE
- 4.3.17.RELEASE
- 4.3.18.RELEASE
- 4.3.19.RELEASE
- 4.3.20.RELEASE
- 4.3.21.RELEASE
- 4.3.22.RELEASE
- 4.3.23.RELEASE
- 4.3.24.RELEASE
- 4.3.25.RELEASE
- 4.3.26.RELEASE
- 4.3.27.RELEASE
- 4.3.28.RELEASE
- 4.3.29.RELEASE
- 4.3.30.RELEASE
Versions in green have been tested.
- spring-test 4.3.30.RELEASE (Spring TestContext Framework)
- javax.servlet-api 3.0.1 (Java Servlet API)
- jstl 1.2 (javax.servlet:jstl)
- junit 4.12 (JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck)
- commons-fileupload 1.3.1 (The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart
file upload functionality to servlets and web applications)
- JDK 1.8
- Maven 3.9.11
|