SPRINGMVC: Upload a single file with Multipartfile, multiple files

Source: Internet
Author: User
Tags file size file upload save file
individual file Upload development steps: 1. Add Apache file upload jar package

First you need to download the jar package for two Apache upload files
Commons-fileupload-1.3.1.jar
Commons-io-2.4.jar
Depending on the project, select the version you are using.
2. Configuring Multipartresolver Processing Files

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

    <bean id= "Multipartresolver"
    class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <property name= "maxuploadsize" value= "5400000"/>
        <property name= "defaultencoding" value= " UTF-8 "/>
    </bean>

Property Description:
Maxuploadsize: The maximum size of the uploaded file, in bytes;
Defaultencoding: The encoding format of the request, which defaults to iso-8859-1. 3. Write File Upload controller

@Controller public class Fileuploadcontroller {private static String Upload_directory = Propertiesutil.get ("Fileuplo

    Ad.directory "," "); @RequestMapping (value = "UploadFile", method = requestmethod.post) public Modelandview uploadfile (@RequestParam ("File" ) {//Multipartfile file) {//Determine if the files are empty if (!file.isempty ()) {try {//Determine if the file directory exists, no
                The file directory = new file (upload_directory) is automatically generated;
                if (!directory.exists ()) {directory.mkdirs (); }//Fail jump View if (File.getsize () > 30000) return new Modelandview ("UPLOADF

                Ail "," msg ", File.getoriginalfilename () +" exceeds the specified size ");
                File save path String FilePath = Filenameutils.concat (Upload_directory, File.getoriginalfilename ());

            Dump Files File.transferto (new file (FilePath)); } catch (Exception e) {E.printstackTrace ();
    }}//Success Jump View return new Modelandview ("Uploadsuccess", "MSG", File.getoriginalfilename ()); }

}


Description
1> uses SPRINGMVC annotation @requestparam to get the contents of the file parameter in the form;
2> multipartfile the Transferto (file dest) method to directly dump the file to the specified path. 4. Writing the test form for the previous paragraph

upload.jsp

<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>

uploadfail.jsp

<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>


Note To add enctype= "Multipart/form-data" to the form label means that the form is to process the file, this is the most basic thing, many people will forget but when the upload error, then go to find the program error, but forget this point 5. Run a single file upload result

Success:

Failed:
multiple file Upload development steps:

Steps are the same, but step 3,4 are slightly different. 3.1 + File upload controllers

    /**
     * Multiple file uploads
     * @param files
     * @return
     *
    /@RequestMapping (value = "Uploadfiles", method = requestmethod.post) Public
    Modelandview UploadFile (@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) {
            //loops get the files in the filename array for
            (int i = 0; I &l T Files.length; i++) {
                multipartfile file = files[i];

                Save File
                String FilePath = Filenameutils.concat (Upload_directory, File.getoriginalfilename ());
                Dump file
                try {
                    File.transferto (new file (FilePath));
                } catch (IOException e) {
                    e.printstacktrace ();
                }
            }
        }

        Jump View
        return new Modelandview ("Uploadsuccess", "msg", files.length+ "files");
    }
4.1 + File upload forms
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>


Description
Front-end forms, multiple filegroups Use the same name: files, the background controller uses @requestparam ("files") multipartfile[] files array to receive. 5.1 Running multiple file upload results

Upload:

Results:

GitHub on Source: https://github.com/ChasingLight/SpringDataJPA.git Extension: 1>multipartfile Common methods

Printing method Results:
1> file type value, Multipartfile.getcontenttype (): Image/jpeg
2> the file component in the form corresponds to the name value, Multipartfile.getname (): File
3> file original name includes suffix name, Multipartfile.getoriginalfilename (): imei_20171204.jpg
4> File size unit is k,multipartfile.getsize (): 27128
5> file is empty, Multipartfile.isempty (): false 2>apache file-related jar package common methods

1>filenameutils.concat (BasePath, fullfilename): Used for stitching directories and file names as file full path, and will use corresponding separators according to the system
2>fileutils.copyurltofile (URL source, File destination, int connectiontimeout, int readtimeout):
Download the file from the specified URL, save to destination, and specify the connection timeout length to read the file timeout.

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.