Multiple file uploads, using the Multipartfile

Source: Internet
Author: User
Tags file upload save file
Basic SPRINGMVC in my previous article has been written, this article mainly explains how to use Springmvc to upload files on the form and multiple files simultaneously upload the steps

SPRINGMVC Basic Tutorial Framework Analysis: http://blog.csdn.net/swingpyzf/article/details/8885459

SPRINGMVC Basic Tutorial Simple Getting Started example: http://blog.csdn.net/swingpyzf/article/details/8904205


File Upload Project source code download address: http://download.csdn.net/detail/swingpyzf/6979915


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

[HTML] view plain copy print? <!--configuration multipartresolver for file uploads using spring Commosmultipartresolver--<beans:bean id= "Multipartresolver" CLA ss= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultencoding= "UTF-8" P:ma Xuploadsize= "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:
[HTML] view plain copy print? <body> Note To add enctype= "Multipart/form-data" to the form label means that the form is to process the file, which is the most basic thing, many people will forget but when the upload error, then go to find the program error, but forget this


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:

[Java] View Plain copy print? Get the Spring default configuration request        @Autowired      using Spring's autowired annotations    private HttpServletRequest request;           /***       *  upload files   Use @requestparam annotations to specify that file on the form is multipartfile       *        *  @param  file        *  @return        */         @RequestMapping ("FileUpload")        public string fileupload (@ Requestparam ("file")  multipartfile file)  {            //  determine if the file is empty            if  (!file.isempty ())  {               try {                   //   File save path                     string filepath = request.getsession (). Getservletcontext (). GetRealPath ("/")  +   "upload/"                             + file.getoriginalfilename ();                    //  Dump Files                     file.transferto (New file (FilePath));                } catch  (exception e)  {                     e.printstacktrace ();                }           }            //  redirection             return  "redirect:/list.html";       }           /***       *  Read all files in the upload file and return to         *        *  @return         */        @RequestMapping ("list")        public  modelandview list ()  {           String  Filepath = request.getsession (). Getservletcontext (). Getrealpath ("/")  +  "upload/";    &NBSP;&NBSP;      modelandview mav = new modelandview ("list");            file uploaddest = new file (FilePath) ;           String[] fileNames =  Uploaddest.list ();           for  (int i =  0; i < filenames.length; i++)  {                //Print out file name                 system.out.println (Filenames[i]);            }           return mav;        }  


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 ()//after going to 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:
[HTML] View Plain copy print? <body>       
2, write the action to handle the form, the original method of saving the file to write a separate method to facilitate common use:
[Java] View Plain copy print? /***       *  Save file        *  @param  file        *  @return        */        private boolean savefile (multipartfile file)  {            //  determine if the file is empty             if  (!file.isempty ())  {                try {                    //  File Save path                     string filepath = request.getsession (). GetServletContext (). Getrealpath ("/")  +  "upload/"                            +  File.getoriginalfilename ();                    //  Dump Files                     file.transferto (New file (FilePath));                    return true;                } catch  (Exception  e)  {                    e.printstacktrace ();                }           }            return false;       }   3, write action:       @ Requestmapping ("Filesupload")        public string filesupload (@ Requestparam ("Files")  multipartfile[] files  {            //determines that the file array cannot be empty and has a length greater than 0           if (files!=null &&files.length>0) {                //Loop gets the files in the file array                for ( int i = 0;i<files.length;i++) {                    MultipartFile file = files[i];                   //Saving files        &Nbsp;            savefile (file);                }            }           //  redirection             return  "redirect:/list.html";        }  
Last Run project upload file:

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.