Springmvc Upload with Multipartfile file

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

<!--configuration multipartresolver for file uploads using spring Commosmultipartresolver--      <beans:bean id= "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:

<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:

Get the Spring default configuration request @Autowired private HttpServletRequest request via spring's autowired annotations; /*** * Upload file with @requestparam annotation to specify that file on the form is multipartfile * * @param file * @return */@Request          Mapping ("FileUpload") public String FileUpload (@RequestParam ("file") Multipartfile file) {//Determine if the files are empty if (!file.isempty ()) {try {//File save path String FilePath = request.getses                  Sion (). Getservletcontext (). Getrealpath ("/") + "upload/" + file.getoriginalfilename ();              Dump Files File.transferto (new file (FilePath));              } catch (Exception e) {e.printstacktrace ();      }}/redirect return "redirect:/list.html"; /*** * Read all files in the upload file and return * * @return */@RequestMapping ("list") public Modelandview List () {String FilePath = request.getsession(). Getservletcontext (). Getrealpath ("/") + "upload/";          Modelandview Mav = new Modelandview ("list");          File Uploaddest = new file (FilePath);          string[] FileNames = Uploaddest.list ();          for (int i = 0; i < filenames.length; i++) {//print out filename 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:

<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:

/*** * Save Files * @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[] F              Iles) {//To determine that the file array cannot be empty and that the length is greater than 0 if (files!=null&&files.length>0) {///loops get the files in the filename array                  for (int i = 0;i<files.length;i++) {multipartfile file = Files[i]; Save File SaveFile(file);      }}/redirect return "redirect:/list.html";   }

  

Springmvc Upload with Multipartfile 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.