SPRINGMVC handles multipart requests.

Source: Internet
Author: User

First, brief

Data in multipart format splits a form into multiple parts (part), and each section corresponds to an input field. In the normal form input field, the text type data is placed in the corresponding section, but if you upload the file, it can be binary in the corresponding part. Similar to this:

TwoConfiguring the multipart parser

Although multipart requests seem complicated, it is easy to handle them in spring MVC. Before writing the Controller method to process file uploads, we had to configure a multipart parser to tell Dispatcherservlet how to read the multipart request.

Spring built-in two Multipartresolver implementations:

    • commonsmultipartresolver: Use Jakarta Commons FileUpload to parse the multipart request;
    • standardservletmultipartresolver: dependent on Servlet 3.0 support for multipart requests (starting with Spring 3.1).

Configuration of the Standardservletmultipartresolver:

1. Declaring beans:

<id= "Multipartresolver"  class= " Org.springframework.web.multipart.support.StandardServletMultipartResolver
in Applicationcontext.xml configuration
        @Bean (name = "Multipartresolver")        public  standardservletmultipartresolver Getstandardservletmultipartresolver () {                returnnew  Standardservletmultipartresolver ();        }
Configuring in the configuration Class

tips:Multipart The name of the parser must be multipartresolver, otherwise it will error.

2. Configure the Upload parameters:

* web. XML configuration

  <servlet>    <Servlet-name>Dispatcherservlet</Servlet-name>    <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>    <Init-param>        <Param-name>Contextconfiglocation</Param-name>        <Param-value>Classpath:applicationContext.xml</Param-value>    </Init-param>    <Load-on-startup>1</Load-on-startup>    <Multipart-config>        <!--upload to/tmp/upload directory -      < Location>/tmp/upload</ Location>        <!--file size is 2M -      <max-file-size>2097152</max-file-size>        <!--the entire request does not exceed 4M -      <max-request-size>4194304</max-request-size>        <!--all files are written to disk -      <File-size-threshold>0</File-size-threshold>    </Multipart-config>  </servlet>  <servlet-mapping>    <Servlet-name>Dispatcherservlet</Servlet-name>    <Url-pattern>/</Url-pattern>  </servlet-mapping>
View Code

* Configure in the configuration class

    @Override    protectedvoid  customizeregistration ( Servletregistration.dynamic registration) {        // upload to/tmp/upload directory, file size is 2M, the entire request does not exceed 4M, And all files are written to disk        registration.setmultipartconfig (new multipartconfigelement ("E:\\upload_ftp"), 2097152,4194304,0));    }
Inherit the Abstractannotationconfigdispatcherservletinitializer configuration class

Configuration of the Commonsmultipartresolver:

1. Declaring beans and configuring upload parameters

    <BeanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver">       <!--set the upload directory/tmp/upload, the maximum file capacity is set to 2M, the maximum memory size is set to 0, indicating that all files will be written to disk; Unable to set the maximum capacity of multipart request overall -        < Propertyname= "Uploadtempdir"value= "/tmp/upload"/>        < Propertyname= "Maxuploadsize"value= "2097152"/>        < Propertyname= "Maxinmemorysize"value= "0"/>    </Bean>
set in Applicationcontext.xml

Difference:1, Commonsmultipartresolver compared to Standardservletmultipartresolver is unable to set the maximum capacity of multipart request overall.

2. Commonsmultipartresolver does not enforce the requirement to set the temporary file path. By default, this path is the temporary directory for the Servlet container. Standardservletmultipartresolver the temporary file path must be set to execute properly. (The upload directory described above is a temporary file path)

Iii. SPRINGMVC Processing Requests

1. Front-end Form form

      <formAction= "/picture"Method= "POST"enctype= "Multipart/form-data">          <inputtype= "File"name= "Picture">          <inputtype= "Submit">      </form>
View Code

tips: You need to set enctype= "Multipart/form-data" to tell Springmvc this is a multipart request.

2. Back-end MVC accepts requests

    @RequestMapping (value = "/picture", method = requestmethod.post)    publicthrows  IOException {        = picture.getname ();         byte [] bytes = picture.getbytes ();        Picture.transferto (new File ("/" +Picture.getoriginalfilename ()));          // The relative path is used when saving to the file system, as configured here. Base on the configured upload directory. That is, the file path e:/upload_ftp/is the saved directory        return "Home";    }
View Code

tips:1, @RequestPart ("Picture"): when the registration form is submitted, the Picture property will be given a byte array containing the corresponding Part 's data ( specified by @RequestPart ). If the user submits the form without selecting the file, the array will be empty (not null). So we can even use byte[] arrays to receive multipart requests without multipartfile.

2, Multipartfile: With the Multipartfile method to receive for us to provide a lot of methods for the next work ...

3, part        partmultipartfile There is not much difference.   In many cases part The name of the method and multipartfilegetsubmittedfilename () corresponds to getoriginalfilename () write () corresponds to transferto ()

    @RequestMapping (value = "/picture", method = requestmethod.post)    publicthrows  IOException {        picture.write ("/" +Picture.getsubmittedfilename ());         return "Home";    }

SPRINGMVC handles multipart requests.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.