Spring MVC uses commons fileupload to implement file upload functionality

Source: Internet
Author: User
Tags ascii hex values

Spring-related jar dependencies were introduced through Maven to build the Spring MVC project.

1, in order to use Commons FileUpload components, need to add dependencies in the Pom.xml;

<Properties>        <spring.version>3.0.7.RELEASE</spring.version>        <junit.version>3.8.1</junit.version>        <fileupload.version>1.2.2</fileupload.version>    </Properties>    <Dependency>        <groupId>Commons-fileupload</groupId>        <Artifactid>Commons-fileupload</Artifactid>        <version>${fileupload.version}</version>    </Dependency>

2, configure Spring MVC, Project successfully started, write JSP page;

<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML>    <Head>        <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">        <title>Errors importing Excel</title>    </Head>    <Body>        <Div>            <!--file uploads are only possible if the form's enctype is set to Multipart/form-data, and the default value for form enctype is: application/x-www-form-urlencoded -            <!--only the Post method will be parsed as a file upload request -            <formAction= "./fileupload"Method= "POST"enctype= "Multipart/form-data">                <!--do not know why, type= "file" This tag must also add the Name property, otherwise when processing the upload, cannot detect the upload file -                <inputtype= "File"name= "Filefield"/>                <inputtype= "Submit"value= "Upload"/>                             </form>            <P><FontColor= "Red">Upload file size limit within 1M</Font></P>        </Div>    </Body></HTML>

Note: The content of the note is still very important, the use of more and more wonderful problems encountered, for the moment have not figured out why, to be resolved later.
Note: To implement the form of uploading a file, you need to specify method= "POST" and enctype= "Multipart/form-data", otherwise you cannot resolve the upload request through the FileUpload component.

3, write controller, called Fileuploadcontroller, in the controller in the upload file processing;

1 @Controller2  Public classFileuploadcontroller {3     4@RequestMapping ("/fileupload")5      PublicString handlefileupload (httpservletrequest request) {6         BooleanFlag =false;7         8         //determine if a file upload request9         if(servletfileupload.ismultipartcontent (Request)) {Ten             //creating a File upload processor OneServletfileupload upload =Newservletfileupload (); A             //limit the size of a single upload file -Upload.setfilesizemax (1l<<24); -              the             Try { -                 //parsing Requests -Fileitemiterator iter =Upload.getitemiterator (request); -                  +                  while(Iter.hasnext ()) { -Fileitemstream item =Iter.next (); +                      A                     if(!Item.isformfield ()) { at                         //is the file upload object, gets the input stream of the uploaded file -InputStream Srcininputstream =Item.openstream (); -                         /*The input stream of the uploaded file is processed in the same way as local file stream processing*/ -                          -                     } -                 } in}Catch(fileuploadexception e) { -System.out.println ("Upload file too large"); to}Catch(IOException e) { +System.out.println ("Problem with file read"); -             } the         } *          $         returnFlag? "Success": "Error";Panax Notoginseng     } -}

Note: Commons FileUpload user Guide http://commons.apache.org/proper/commons-fileupload/using.html;
Note: To determine the upload request and processing using the streaming API http://commons.apache.org/proper/commons-fileupload/streaming.html;
The contents are as follows:

Note: The first time you look at the user guide of the Commons FileUpload component, I feel that I don't know what to do, in fact the parsing the request section of user guides has given a very clear explanation. It is possible to determine whether a file upload request is by using servletfileupload.ismultipartcontent (request) directly through the corresponding requests processing method, by!item.isformfield () to determine whether the file is uploaded to the object ;

4, the FileUpload component uploads the file, obtains the common domain parameter value and the file domain input stream;
The Enctype property of the form form for HTML elements specifies how the form data should be encoded before being sent to the server. The enctype default value for the form is "application/x-www-form-urlencoded", and all characters are encoded before the form is sent to the server (spaces are converted to "+" plus signs, and special symbols are converted to ASCII HEX values); For file uploads, The form form enctype= "Multipart/form-data", at which time the form form is not encoded, and the parameter value cannot be obtained through Request.getparameter ("ParameterName") in the requested handler function ;

However, the parameter values can be obtained by other means;

1     /**2 * Get the parameters of page pass, store with map, fieldname as key value, normal domain store value, file upload domain store file input stream3      * @paramRequest4      * @return5      */6     PrivateMap<string, object>getparameters (HttpServletRequest request) {7map<string, object> parameters =NewHashmap<string, object>();8         9         //The default is to allow storage of up to 1024 bytesTenDiskfileitemfactory factory =Newdiskfileitemfactory (); One          A         if(servletfileupload.ismultipartcontent (Request)) { -Servletfileupload upload =Newservletfileupload (factory); -              the             Try{ -list<fileitem> items =upload.parserequest (request); -              -                  for(Iterator<fileitem> iter =items.iterator (); Iter.hasnext ();) { +Fileitem item =Iter.next (); -                      +                     if(Item.isformfield ()) { A                         //normal fields, taking parameter values at Parameters.put (Item.getfieldname (), item.getstring ()); -}Else{ -                         //file upload domain, take input stream - Parameters.put (Item.getfieldname (), Item.getinputstream ()); -                     } -                 } in}Catch(Exception Exception) { - exception.printstacktrace (); to             } +         } -          the         returnparameters; *}

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.