How to upload files in "Springmvc" Springmvc

Source: Internet
Author: User

Components used: You can choose the version according to your own situation
<!--uploading a dependency package -            <Dependency>                <groupId>Commons-fileupload</groupId>                <Artifactid>Commons-fileupload</Artifactid>                <version>1.3.2</version>            </Dependency>            <!--commons-upload Dependency Pack begin -            <Dependency>                <groupId>Commons-io</groupId>                <Artifactid>Commons-io</Artifactid>                <version>2.5</version>            </Dependency>            <!--Commons-upload Dependency Package End -

Xx-servlet.xml file Configuration

<!--SPRINGMVC You need to configure the Multipartresolver processor when uploading files -    <BeanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!--The default encoding is Iso-8859-1 -        < Propertyname= "Defaultencoding"value= "UTF-8"/>        <!--The upload size limit for 100mb,maxuploadsize is configured with the number of bytes -        < Propertyname= "Maxuploadsize"value= "104857600"/>        <!--Set The maximum allowed size (in bytes) before uploads is refused -        < Propertyname= "Maxinmemorysize"value= "40960"/>        <!--Uploadtempdir The temporary path of the uploaded file, after the file is uploaded, temporary files in the temporary directory will be automatically cleared -        < Propertyname= "Uploadtempdir"value= "Fileupload/temp"/>    </Bean>

Tips: About Uploadtempdir, you need to create web-inf/fileupload/temp these two folders, because the program will not be created automatically, if not created, will be directly error, as to what is called, how the hierarchy, according to their own circumstances can be modified;

Maxuploadsize: The number of bytes is configured;
Maxinmemorysize:set The maximum allowed size (in bytes) before uploads is refused

If the upload process, garbled, you can configure the following filter in Web. XML, specifying the encoding format as Utf-8;

    <Filter>        <Filter-name>Characterencodingfilter</Filter-name>        <Filter-class>Org.springframework.web.filter.CharacterEncodingFilter</Filter-class>        <!--supports asynchronous -        <async-supported>True</async-supported>        <Init-param>            <Param-name>Encoding</Param-name>            <Param-value>UTF-8</Param-value>        </Init-param>        <Init-param>            <Param-name>Forceencoding</Param-name>            <Param-value>True</Param-value>        </Init-param>    </Filter>    <filter-mapping>        <Filter-name>Characterencodingfilter</Filter-name>        <Url-pattern>/*</Url-pattern>    </filter-mapping>

Front-end HTML:

If you want to select multiple file uploads at once, you can set multiple; If you upload one file at a time, do not set this property;

In addition,enctype= "Multipart/form-data" must be set;

<formname= "Form2"Action= "/rest/upload/springupload"Method= "POST"enctype= "Multipart/form-data">    <H1>Uploading files using the classes provided by spring MVC</H1>    <inputtype= "File"name= "File"multiple= "multiple">    <inputtype= "Submit"value= "Upload"/></form>

Background code:
    /** Using spring-provided methods of uploading files*/@RequestMapping (Value= "Springupload", method =requestmethod.post) PublicModelandview springupload (HttpServletRequest request)throwsIllegalStateException, IOException {LongStartTime =System.currenttimemillis (); //initializes the current context to commonsmultipartresolver (multipart parser)Commonsmultipartresolver Multipartresolver =NewCommonsmultipartresolver (Request.getsession (). Getservletcontext ()); //Check if there is a enctype= "Multipart/form-data" in the form        if(Multipartresolver.ismultipart (Request)) {//Change request to multi-part RequestMultiparthttpservletrequest multirequest =(multiparthttpservletrequest) request; //get all the file names in MultirequestIterator FileNames =Multirequest.getfilenames (); //the upload folder exists, does not exist, and the final format is/uploadfile/2017-06-01/{file name} String Realpath = Request.getsession (). Getservletcontext (). Getrealpath ("/uploadfile/") +Datetimeutils.getnow (). toString (); File Pathfile=NewFile (Realpath); if(!pathfile.exists ())            {Pathfile.mkdirs (); }             while(Filenames.hasnext ()) {//traverse all files at once               list<multipartfile> fileList = multirequest.getfiles (Filenames.next (). toString ());  if (fileList! = null) {   for (Multipartfile file:filelist                        {String Path = Realpath + "/" + file.getoriginalfilename ();                        System.out.println ("Upload path:" + path);  // upload file.transferto (new  File (path)); }                }            }        }        LongEndTime =System.currenttimemillis (); System.out.println ("Run Time:" + string.valueof (endtime-starttime) + "MS"); return NewModelandview ("Fileupload/success"); }

Final effect:

Reference:

# About Commonsmultipartresolver Configuration

https://docs.spring.io/spring/docs/1.2.x/javadoc-api/org/springframework/web/multipart/commons/ Commonsmultipartresolver.html

Http://www.cnblogs.com/fjsnail/p/3491033.html # There is a problem, that is, method three does not solve the situation when uploading multiple resources;

How to upload files in "Springmvc" Springmvc

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.