Most web applications require multipart file upload functionality. Spring MVC makes it extremely easy to handle this otherwise cumbersome feature. It provides two built-in implementations of MultiPartResolvers
: CommonsMulipartResolver
for Apache Commons FileUpload and StandardServletMultipartResolver
for the Servlet 3.0 API.
Since most modern web applications use a Servlet 3.0 container, let's see how the FileUpload functionality can be handled using StandardServletMultipartResolver
with the help of following example:
MultipartResolver
in your servlet-context.xml
file (or add it programmatically if you are using a Java configuration):<beans:bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"> </beans:bean>
DispatcherServlet
in your web.xml
(or JavaConfig) file:<servlet> <servlet-name>appServlet</servlet-name> ... <multipart-config> <location>/tmp/servlet-uploads</location> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config> </servlet>
<form:form action="../${user.id}/profileForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="txtUserName">Choose File</label> <input type="file" name="profileImage"/> </div> <button type="submit" class="btn btn-success">Upload</button> <a href="../${user.id}" class="btn btn-primary">Cancel</a> </form:form>
@RequestMapping(path = "/{userId}/profileForm", method = RequestMethod.POST) public String uploadProfileImage(@PathVariable("userId") Long userId, @RequestParam("profileImage") MultipartFile file) throws IOException { User user = userService.findById(userId); String rootDir = FILE_ROOT_DIR + "/" + user.getId(); if (!file.isEmpty()) { java.io.File fileDir = new java.io.File(fileSaveDirectory); if (!fileDir.exists()) { fileDir.mkdirs(); } FileCopyUtils.copy(file.getBytes(), new java.io.File(rootDir + "/" + file.getOriginalFilename())); File profileImageFile = this.userService.addProfileImage(userId, file.getOriginalFilename()); } return "redirect:/users/" + userId; }