Springmvc File upload configuration, multiple file uploads, use of Multipartfile instances _java

Source: Internet
Author: User

The basic SPRINGMVC has been written in my last article, which explains how to use Springmvc to upload files on a form and upload multiple files at the same time.

File Upload Project source code download address: Demo

First, the configuration file:

Springmvc used Multipartfile to upload files, so we're going to first configure the Multipartresolver: To work with the file in the form

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

Where the attributes are detailed:

    • Defaultencoding= "UTF-8" is the encoded format of the request, and the default is Iso-8859-1
    • Maxuploadsize= "5400000" is the size of the uploaded file, in bytes
    • Uploadtempdir= "Fileupload/temp" as a temporary path to the uploaded file

Two, create a simple upload form:

<body> 
 
 

Note To add enctype= "Multipart/form-data" to the form label to indicate that it is the most basic thing to do with a file, many people forget to look for bugs in the program after uploading an error but forget it

Third, write upload control class

1. Create a control class: Fileuploadcontroller and a page that returns results list.jsp

2. Write the action of submitting the form:

Get the request @Autowired the spring default configuration through spring's autowired annotations private httpservletrequest request; /*** * Upload files use @requestparam annotations to specify that the file on the form is multipartfile * * @param file * @return */@RequestMapping ( "FileUpload") public String FileUpload (@RequestParam ("file") Multipartfile file) {//To determine if the file is an empty if (!file.isem Pty ()) {try {//File save path String FilePath = Request.getsession (). Getservletcontext (). Getrealpath (" 
        /") +" upload/"+ file.getoriginalfilename (); 
      Dump file File.transferto (new file (FilePath)); 
      catch (Exception e) {e.printstacktrace (); 
  }//redirect return "redirect:/list.html"; 
    /*** * Read all files in the uploaded 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 methods commonly used in the Multipartfile class are:

    • String getContentType ()//Get file MIME type
    • InputStream getInputStream ()//after go to file stream
    • String getName ()//Get the name of the file component in the form
    • String getoriginalfilename ()//Get original of uploaded file
    • Long GetSize ()//Get file byte size, unit byte
    • Boolean IsEmpty ()/IS NULL
    • The void TransferTo (file dest)//is saved to a destination file.

Four, multiple file upload.

Multi-File upload is actually very simple, and upload other same parameters like a checkbox, the form uses the same name, and then the Multipartfile parameter class is defined as an array in the action.

Next implementation:

1. Create a form to upload multiple files:

<body> 
   
 

2, write processing form action, 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 an empty 
    if (!file.isempty ()) { 
      try { 
        //File save path 
        String FilePath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/" 
            + file.getoriginalfilename (); 
        Dump file 
        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 { 
    // To determine that the file array cannot be empty and that the length is greater than 0 
    if (files!=null&&files.length>0) { 
      ///loop Gets the file in the files array for 
      (int i = 0;i< files.length;i++) { 
        multipartfile file = files[i]; 
        Save files 
        savefile (file); 
      } 
    REDIRECT Return 
    "redirect:/list.html"; 
  } 

Last Run project upload file:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.