Spring MVC file upload

Posted by brij_theinvader on Sat, 13 Jul 2019 20:40:14 +0200

Spring MVC provides direct support for file upload through Plug and Play MultipartResolver. Spring uses Jakarta Commons File Upload technology to implement a MultipartResolver implementation class: Commons MultipartResolver.

MultipartResolver is not assembled by default in the Spring MVC context, so file upload cannot be processed by default. If you want to use Spring's file upload function, you need to configure MultipartResolver in the context first.

 

1. Configure MultipartResolver

Next, use Commons MultipartResolver to configure a MultipartResolver parser.

<!-- File upload -->
<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
  p:defaultEncoding="UTF-8"//The encoding format of the request is ISO-8859-1 by default.
  p:maxUploadSize="5000000"//(2) Upload file size limit, in bytes (5MB)
  p:uploadTempDir="file://d:/temp"/>//(3) Temporary path of uploading files

defaultEncoding must be consistent with the page Encoding attribute of the user JSP in order to read the form correctly. uploadTempDir is a temporary directory used in the process of file upload. When the file upload is completed, the temporary files in the temporary directory will be automatically cleared.

In order for Commons MultipartResolver to work properly, you must first add the classpackages of Jakarta Commons FileUpload and Jakarta Commons io to the classpath.

 

2. Writing Controller and File Upload Form Page

Add a method in UserController to handle user profile uploads, as shown in the following code.

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping(value = "/uploadPage")//
    public String updatePage() {    
        return "uploadPage";
    }
    
    @RequestMapping(value = "/upload")
    public String updateThumb(@RequestParam("name") String name,
                              @RequestParam("file") MultipartFile file) throws Exception{
                              //②Uploaded files are automatically bound to MultipartFile in
        if (!file.isEmpty()) {
            file.transferTo(new File("d:/temp/"+file.getOriginalFilename()));
            return "redirect:success.html";
        }else{
            return "redirect:fail.html";
        }
    }
}

Spring MVC binds uploaded files to MultipartFile objects. MultipartFile provides methods to obtain the content and name of uploaded files. It can also store files into hardware by transferTo(), as described below.

1) byte[] getBytes(): Get file data.

2) String getContentType(): Get file MIME types, such as image/pjpeg, text/plain, etc.

3) InputStream getInputStream(): Get the file stream.

4) String getName(): Gets the name of the file component in the form.

5) String get Original Filename (): Get the original name of the uploaded file.

6) long getSize(): Gets the byte size of the file in Byte.

7) boolean isEmpty(): Do you have uploaded files?

8) void transfer to (File dest): You can use this file to save the uploaded file to a target file.

The form responsible for uploading files differs from the general form in that the encoding type of the form must be multipart/form-data.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Please upload user profile</title>
    </head>
    <body>
        <h1>
            Please select the uploaded avatar file
        </h1>
        <form method="post" action="<c:url value="/user/upload.html"/>" enctype="multipart/form-data">//Specify the form content type to support file upload
            <input type="text" name="name" />
            <input type="file" name="file" />//(2) Component name of uploaded file
            <input type="submit" />
        </form>
    </body>
</html>

Topics: Python Spring encoding JSP Java