1. Maven introduces the required jar package (or download it yourself)
<Dependency> <groupId>Commons-io</groupId> <Artifactid>Commons-io</Artifactid> <version>2.4</version> </Dependency> <Dependency> <groupId>Commons-fileupload</groupId> <Artifactid>Commons-fileupload</Artifactid> <version>1.3.1</version> </Dependency>
2. Configure Spring file
<!--multipart File Upload - <BeanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver"> < Propertyname= "Defaultencoding"value= "Utf-8"></ Property> < Propertyname= "Maxuploadsize"value= "10485760000"></ Property> < Propertyname= "Maxinmemorysize"value= "40960"></ Property> </Bean>
3, form add enctype= "Multipart/form-data"
<HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title></Head><Body> <H2>Uploading multiple file instances</H2> <formAction= "/upload/filesupload"Method= "POST"enctype= "Multipart/form-data"> <P>Select File:<inputtype= "File"name= "Files"></p> <P>Select File:<inputtype= "File"name= "Files"></p> <P><inputtype= "Submit"value= "Submit" ></p> </form> </Body></HTML>
5. Controller part
ImportJava.io.File;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.multipart.MultipartFile, @Controller @requestmapping ("/upload") Public classUploadcontroller {//Request for spring's default configuration through spring's autowired annotations /*** * Save file *@paramfile *@return */ Private BooleansaveFile (multipartfile file, String path) {//determine if the file is empty if(!File.isempty ()) { Try{File filepath=NewFile (path); if(!filepath.exists ()) filepath.mkdirs (); //File Save pathString Savepath = path +File.getoriginalfilename (); //Dump FilesFile.transferto (NewFile (Savepath)); return true; } Catch(Exception e) {e.printstacktrace (); } } return false; } @RequestMapping ("/filesupload") PublicString Filesupload (@RequestParam ("Files") multipartfile[] files) {String path= "e:/upload/"; //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, path); } } // redirect return"Redirect:/list.html"; } }
Run as follows:
SPRINGMVC implement multipartfile Multi-file upload