Springmvc File upload configuration, multi-file upload, use of multipartfile

Source: Internet
Author: User
Tags save file

One, the configuration file:
Springmvc used the Multipartfile to upload the file, so we'll first configure the Multipartresolver: To process the form file

<!--Configure Multipartresolver for file uploads using spring's commosmultipartresolver -      <Beans:beanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver"p:defaultencoding= "UTF-8"p:maxuploadsize= "5400000"P:uploadtempdir= "Fileupload/temp"       >      </Beans:bean>  

The attributes are detailed in the following:
Defaultencoding= "UTF-8" is the requested encoding format, the default is Iso-8859-1
Maxuploadsize= "5400000" is the size of the uploaded file, in bytes
Uploadtempdir= "Fileupload/temp" is the temporary path for uploading files

Second, create a simple upload form:

    <formAction= "/upload"Method= "POST"enctype= "Multipart/form-data">        <label>Select File:</label>        <inputtype= "File"name= "File5">        <inputtype= "Submit"value= "Submit">    </form>

Note To add enctype= "Multipart/form-data" to the form label means that the form is to be processed by the file.

Third, write the Upload control class

1. Create a control class: Fileuploadcontroller and a page that returns results list.jsp
2. Write the action to submit the form:

@Controler Public classFileUpload {//Request for spring's default configuration through spring's autowired annotations@AutowiredPrivateHttpServletRequest request; /*** * upload files with @requestparam annotations to specify that file on the form is multipartfile * *@paramfile *@return     */@RequestMapping ("FileUpload")     PublicString FileUpload (@RequestParam ("File") multipartfile file) {//determine if the file is empty        if(!File.isempty ()) {            Try {                //File Save pathString FilePath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/" +File.getoriginalfilename (); //Dump FilesFile.transferto (NewFile (FilePath)); } Catch(Exception e) {e.printstacktrace (); }        }        // redirect        return"Redirect:/list.html"; }    /*** * Read all files in the upload file and return * *@return     */@RequestMapping ("List")     PublicModelandview list () {String FilePath= Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/"; Modelandview Mav=NewModelandview ("list"); File uploaddest=NewFile (FilePath); String[] FileNames=uploaddest.list ();  for(inti = 0; i < filenames.length; i++) {        //print out the file nameSystem.out.println (Filenames[i]); }        returnMav; }}

3. Use SPRINGMVC annotation Requestparam to specify the file parameters in the form;
4. Specify a Web project path to save the file
5, through the Multipartfile transferto (file dest) This method to dump the file to the specified path.

This is the end of the basic file upload.


Some common methods of the Multipartfile class are:


String getContentType ()//Get file MIME type
InputStream getInputStream ()//Get file stream
String getName ()//Gets the name of the file component in the form
String getoriginalfilename ()//Gets the original of the uploaded file
Long GetSize ()//Gets the byte size of the file, in units of byte
Boolean isEmpty ()//Is empty
void TransferTo (file dest)//saved to a destination file.

Four, multiple file upload.

Multi-file uploads are really simple, and uploading the same parameters as a checkbox, the form uses the same name, and the action will define the Multipartfile parameter class as an array.
Next implementation:

1. Create a form that uploads multiple files:

    <formAction= "filesupload.html"Method= "POST"enctype= "Multipart/form-data">          <P>Select File:<inputtype= "File"name= "Files">          <P>Select File:<inputtype= "File"name= "Files">          <P>Select File:<inputtype= "File"name= "Files">          <P>              <inputtype= "Submit"value= "Submit">      </form>  

2, write the action to handle the form, the original method of saving the file to write a separate method to facilitate common use:

@Controler Public classFileUpload {/*** * Save file *@paramfile *@return     */    Private BooleansaveFile (multipartfile file) {//determine if the file is empty        if(!File.isempty ()) {            Try {                //File Save pathString FilePath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/" +File.getoriginalfilename (); //Dump FilesFile.transferto (NewFile (FilePath)); return true; } Catch(Exception e) {e.printstacktrace (); }        }        return false; }    //3. Write Action:@RequestMapping ("Filesupload")     PublicString Filesupload (@RequestParam ("Files") multipartfile[] files) {//determine that the file array cannot be empty and is longer than 0        if(Files! =NULL&& files.length > 0) {            //loop to get the files in the file array             for(inti = 0; i < files.length; i++) {Multipartfile file=Files[i]; //Save FilesaveFile (file); }        }        // redirect        return"Redirect:/list.html"; }}

Last Run project upload file:

La La la

Springmvc File upload configuration, multi-file upload, use of multipartfile

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.