Spring 4 Official Document Learning (11) Web MVC Framework multipart (file upload) support

Source: Internet
Author: User


1. Introduction

Spring's built-in multipart support handles file uploads in Web apps. You can enable this support--through pluggable multipartresolver objects, they are all defined in the org.springframework.web.multipart package. Spring provides a multipartresolver implementation that works with Commons FileUpload , or with servlet 3.0 multipart request resolution.

By default, spring does not handle multipart, because some developers want to handle them by themselves. You can let spring handle it-by adding a multipart resolver to the context of the Web App. Each request will be checked to see if it contains a multipart. If not, release it. If so, the multipartresolver declared in your context will be used to handle it. After that, you can treat the multipart attribute in your request like any other attribute.

2, combined with Commons fileupload to use Multipartresolver

The following example illustrates how to use Commonsmultipartresolver:

 <  bean  id  = "Multipartresolver"   class  = "Org.springframework.web.multipart.commons.CommonsMultipartResolver"  >  <!--  one of the properties available; The maximum file size in bytes  -->  <
    property  name  = "Maxuploadsize"   value  = "100000"  />  </ bean  >  

Of course, you also need to put the jars in your classpath, so that it can work properly. In this example, you need to use Commons-fileupload.jar.

When spring Dispatcherservlet detects a multi-part request, it activates the declared resolver and gives the request to it. The resolver encapsulates the current httpservletrequest into a multiparthttpservletrequest, which supports multipart file uploads. By using Multiparthttpservletrequest, you can get information about the multiparts contained in the request in controllers, and you can actually access these multipart files.

3, combined with servlet 3.0来 use Multipartresolver

In order to use Servlet 3.0-based multipart parsing, you need to tag dispatcherservlet with a "multipart-config" part-in XML, or, Mark a javax.servlet.MultipartConfigElement in the coded servlet registration, or, in the case of a custom servlet class, Use javax.servlet.annotation.MultipartConfig annotations. The provisioning settings, such as the maximum size or storage location, need to be applied at the servlet registration level because Servlet 3.0 does not allow these settings to be done by Multipartresolver!

Once the servlet 3.0 multipart parsing is enabled, you can add the Standardservletmultipartresolver to your spring configuration:

<id= "Multipartresolver"        class= " Org.springframework.web.multipart.support.StandardServletMultipartResolver "></ Bean >

4. process file upload in form

First, create a form with file input that allows the user to upload. Encoding attribute (enctype= "Multipart/form-data") tells the browser to encode forms in multipart request form:

<HTML>    <Head>        <title>Upload a file please</title>    </Head>    <Body>        <H1>Please upload a file</H1>        <formMethod= "POST"Action= "/form"enctype= "Multipart/form-data">            <inputtype= "text"name= "Name"/>            <inputtype= "File"name= "File"/>            <inputtype= "Submit"/>        </form>    </Body></HTML>

The next step is to create a controller to handle the file upload. As follows:

@Controller Public classFileuploadcontroller {@PostMapping ("/form")     PublicString Handleformupload (@RequestParam ("name") String name, @RequestParam ("File") multipartfile file) {if(!File.isempty ()) {            byte[] bytes =file.getbytes (); //Store the bytes somewhere            return"Redirect:uploadsuccess"; }        return"Redirect:uploadfailure"; }}

Note the @requestparam parameter is mapped to the INPUT element declared in the form. In this example, byte[] is not involved, but you can still save it to the database, file system, and so on.

When using Servlet 3.0 multipart parsing, you can also use Javax.servlet.http.Part:

@Controller  Public class Fileuploadcontroller {    @PostMapping ("/form")    public String handleformupload (@ Requestparam ("name") String name,            @RequestParam ("file") part file) {        =  File.getinputstream ();         // Store bytes from uploaded file somewhere        return "Redirect:uploadsuccess";    }}

5. Handling file upload requests from coded clients

Multipart requests can also come from non-browser clients-in the rest-style service scenario. All of the above examples and configurations apply to this scenario. However, unlike browsers, coded clients can also send more complex data for a specific content type-for example, a multipart request data with a file and JSON format:

Post/someurlcontent-type:multipart/mixed--edt7tfrdusa7r3lnqc79vxuhiimlatb7pqg7vpcontent-disposition:form-data; Name= "Meta-data" Content-type:application/json; charset=utf-8content-transfer-encoding:8bit{    "name": "Value"}-- Edt7tfrdusa7r3lnqc79vxuhiimlatb7pqg7vpcontent-disposition:form-data; Name= "File-data"; Filename= "File.properties" Content-type:text/xmlcontent-transfer-encoding:8bit ... File Data ...

You can use the @requestparam ("Meta-data") String metadata to access the "Meta-data" section. However, you may prefer to receive a strongly typed object, which is initialized by the JSON-formatted data in the request, very similar to @requestbody using Httpmessageconverter to turn a Non-multipart request body into the target object.

At this point, you can use @requestpart annotations instead of @requestparam annotations. It allows you to focus on a specific multipart content that is httpmessageconverter to its ' Content-type ' header section.

@PostMapping ("/someurl") public String onSubmit (@RequestPart ("Meta-data") MetaData MetaData,        @RequestPart ("File-data") multipartfile file) {    // ... }

Note that multipartfile can be accessed arbitrarily by @requestparam or @requestpart. However, the @RequestPart ("Meta-data") metadata here is the JSON content that reads its ' Content-type ' header section, and use the Mappingjackson2httpmessageconverter to convert.

Spring 4 Official Document Learning (11) Web MVC Framework multipart (file upload) support

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.