Handling file uploads

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:

  1. Register your 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>
  2. Add multipart configuration support to your 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>
  3. Make sure that the location you provided in the previous section really exists. Create the directory if it doesn't.
  4. Create the web form with an input file element in it. This sample JSP snippet uploads a user's profile image:
    <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>
  5. Create the request handler method in your Controller:
    @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;
    }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset