One, a brief introduction

In a javaWeb project, the file upload function is almost essential. I often encounter it in the project development, and did not pay much attention to it before. Today, I have time to learn this knowledge, so I will learn SpringMVC single file and multiple file upload this part of the knowledge to make notes.

Two, single file upload

1, page

For a simple form submission example, file upload requires setting the form submission method to POST and encType to “multipart/form-data”.

<form action="${pageContext.request.contextPath}/test/upload.do" method="post" enctype="multipart/form-data">
    <input type="file" name="img"><br /> 
    <input type="submit" name="Submit">
</form>Copy the code

2. Controller

In the Controller handler, the MultipartFile object is used as a parameter to receive the file uploaded by the front end, as described in the code comments.

@Controller
@RequestMapping("/test")
public class MyController {

    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    // The MultipartFile variable name is the same as the name of the input tag of type file in the form, so the framework automatically uses the MultipartFile object to receive the uploaded file. You can also use @requestParam ("img") to specify the corresponding parameter name
    public String upload(MultipartFile img, HttpSession session)
            throws Exception {
        // If there is no file upload, MultipartFile will not be null, you can call getSize() to get the size of the file to determine whether there is an upload file
        if (img.getSize() > 0) {
            // Get the actual root path of the project on the server, such as /home/tomcat/webapp/ project name /images
            String path = session.getServletContext().getRealPath("images");
            // Get the original name of the file, such as beauty.png
            String fileName = img.getOriginalFilename();
            // You can use the original file name to restrict the type of the file to be uploaded. For example, you can only upload JPG and PNG image files
            if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
                File file = new File(path, fileName);
                img.transferTo(file);
                return "/success.jsp"; }}return "/error.jsp"; }}Copy the code

3. Springmvc. XML configuration

Using the MultipartFile object to receive files uploaded from the front end, you also need to configure the following in the SpringMVC configuration file:

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> ... <! - note: The id of the CommonsMultipartResolver is fixed. Immutable - > < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.Com monsMultipartResolver" > <! <property name="defaultEncoding" value=" UTF-8 "/> <! -- The unit is byte. The total uploaded file size is not limited by default. The total uploaded file size is not greater than 1 MB (1 x 1024 x 1024) --> <property name="maxUploadSize" value="1048576"/> <! -- Similar to maxUploadSize, but maxUploadSizePerFile limits the size of each uploaded file. <property name="maxUploadSizePerFile" value="1048576"/> </bean> <! Set up a simple exception resolver, When a file upload more than size limit jump - > < bean class = "org. Springframework. Web. Servlet. Handler. SimpleMappingExceptionResolver" > < property name="defaultErrorView" value="/error.jsp"/> </bean> </beans>Copy the code

The CommonsMultipartResolver property values in the configuration file above are not required, or you may omit them altogether. Now that you have a single file to upload, let’s look at multiple file uploads.

3. Upload multiple files

Multifile uploads are also simple. Single-file uploads are received by the Controller using the MultipartFile object as a parameter, while multifile uploads are received by the array of MultipartFile objects.

1, page

This page has several input tags of type file with the same name value, and the rest are the same as the single file upload page.

<form action="${pageContext.request.contextPath}/test/upload.do" method="post" enctype="multipart/form-data">
    file 1: <input type="file" name="imgs"><br /> file 2 : <input type="file" name="imgs"><br /> file 3 : < form> <br /> < form type="submit" name=" submit" >Copy the code

2. Controller

The processing method in the controller uses the MultipartFile[] array as the receiving parameter, which cannot be used directly. The parameters need to be corrected. Please refer to the code comments for details.

@Controller
@RequestMapping("/test")
public class MyController {

    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    MultipartFile[] imgs refers to the name of the input tag of multiple types of file in the page, but the framework only encapsulates one file into a MultipartFile object.
    / / not multiple files will be encapsulated into a MultipartFile [] array, use will quote directly [Lorg. Springframework. Web. Multipart. MultipartFile;. < init > () error,
    @requestParam ("imgs") MultipartFile[] files
    public String upload(@RequestParam MultipartFile[] imgs, HttpSession session)
            throws Exception {
        for (MultipartFile img : imgs) {
            if (img.getSize() > 0) {
                String path = session.getServletContext().getRealPath("images");
                String fileName = img.getOriginalFilename();
                if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
                    File file = newFile(path, fileName); img.transferTo(file); }}}return "/success.jsp"; }}Copy the code

In the same way, multiple files uploaded from the front end of the MultipartFile array need to be configured in the SpringMVC configuration file. The configuration is the same as that of the single file uploaded from the springmvc. In this way, you can upload multiple files.

Iv. Synthesis of various file uploading scenarios

Of course, in the development of the project, the scenario may not be so simple, the above multi-file upload is one file after the selection of upload (i.e. multiple input tags with the same name), what if my project only need one input tag can be multiple files at a time? Or a page with multiple file uploads selected one by one, multiple file uploads selected one at a time, and single file uploads? MultipartFile[] is easy to use.

1, page

Here, “multiple file upload with multiple files selected at once” simply adds the multiple attribute to the input tag.

<form action="${pageContext.request.contextPath}/test/upload.do" method="post" enctype="multipart/form-data"<br /> <input type="file" name="imgs1" multiple><br /> <br /> Select multiple files at a time to upload: <br />< input type="file" name="imgs2"><br />< input type="file" name="imgs2"><br /><br /> < br / > < input type = "file" name = "imgs3" > < br / > < br / > < input type = "submit" name = "submit" > < / form >Copy the code

2. Controller

@Controller
@RequestMapping("/test")
public class MyController {

    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    public String upload(@RequestParam MultipartFile[] imgs1,@RequestParam MultipartFile[] imgs2,@RequestParam MultipartFile[] imgs3, HttpSession session)
            throws Exception {
        String path = session.getServletContext().getRealPath("images");
        for (MultipartFile img : imgs1) {
            uploadFile(path, img);
        }
        for (MultipartFile img : imgs2) {
            uploadFile(path, img);
        }
        for (MultipartFile img : imgs3) {
            uploadFile(path, img);
        }
        return "/success.jsp";
    }

    private void uploadFile(String path, MultipartFile img) throws IOException {
        if (img.getSize() > 0) {
            String fileName = img.getOriginalFilename();
            if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
                File file = newFile(path, fileName); img.transferTo(file); }}}}Copy the code

MultipartFile[] is so powerful that it is recommended to use MultipartFile[] as the file receiving parameter in your project development.

Fifth, expand

Class MultipartFile ();

String getContentType()// Get the file MIME type
InputStream getInputStream()// Get the file stream
String getName() // Get the name of the file component in the form
String getOriginalFilename() // Get the original name of the uploaded file
long getSize()  // Get the file size in bytes
boolean isEmpty() // Whether it is empty
void transferTo(File dest) Copy the code

2, CommonsMultipartResolver attribute resolution

DefaultEncoding: indicates the defaultEncoding used to resolve request requests, ISO is used when this is not specified according to the Servlet specification- 8859.- 1. DefaultEncoding is ignored when the request specifies its encoding format. UploadTempDir: Sets the temporary directory for uploading files. Default is the temporary directory of the Servlet container. MaxUploadSize: Sets the maximum file size, in bytes, that can be uploaded. When set to- 1Is unlimited. The default value is- 1. MaxUploadSizePerFile: similar to maxUploadSize, except that maxUploadSizePerFile limits the size of each uploaded file, while maxUploadSizePerFile limits the total uploaded file size. MaxInMemorySize: Sets the maximum number of bytes that can be written to memory during file upload. The default value is10240. ResolveLazily:true, enable deferred file resolution to catch file size exceptions in UploadAction.Copy the code

Sixth, pay attention to

  1. In the development process, it is suggested that the abnormality in the configuration file parser (SimpleMappingExceptionResolver) commented out first, convenient for us to see the error.
  2. Sometimes uploading errors occur because we set a limit on the size of uploaded files in the configuration file. You don’t have to set this limit, but I suggest you add this limit. The specific file size limit depends on the project situation of your company.
  3. When SpringMVC uses MultipartFile to receive uploaded files, it depends on two JAR packages: commons-fileupload-1.3.3.jar and commons-io-2.5.jar.