1.form enctype= "Multipart/form-data" This is required to upload files
2.applicationcontext.xml <bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "/> File upload configuration is not limited
3. Jar packages that require commons.fileupload and Commons.io
Spring's configuration file
<!--SPRINGMVC You need to configure the Multipartresolver processor when uploading files - <BeanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver"> < Propertyname= "Defaultencoding"value= "UTF-8"/> <!--Specifies that the total size of the uploaded file cannot exceed 200KB. Note the limitations of the Maxuploadsize attribute are not for individual files, but for the sum of the capacity of all files - < Propertyname= "Maxuploadsize"value= "200000"/> </Bean> <!--Springmvc throws org.springframework.web.multipart.MaxUploadSizeExceededException when the upload file limit is exceeded - <!--This exception is thrown when Springmvc checks the uploaded file information and is not in the Controller method at this time . - <BeanID= "Exceptionresolver"class= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> < Propertyname= "Exceptionmappings"> <Props> <!--automatically jump to/WEB-INF/FTL/COMMON/ERROR_FILEUPLOAD.FTL page when encountering Maxuploadsizeexceededexception exception - <propKey= "Org.springframework.web.multipart.MaxUploadSizeExceededException">/common/error_fileupload</prop> </Props> </ Property> </Bean>
Controller
Packagecom.zyz.action;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.ModelMap;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.multipart.MultipartFile;Importjavax.servlet.http.HttpServletRequest;ImportJava.io.File;Importjava.util.Date;/*** Created by Zyz on 2016-8-26.*/@Controller Public classuploadaction {@RequestMapping (value= "/uploadform", method =requestmethod.get) PublicString Uploadform () {return"Uploadform"; } @RequestMapping (Value= "/upload", method =requestmethod.post) PublicString Upload (@RequestParam (value = "File", required =false) multipartfile file, httpservletrequest request, Modelmap model) {SYSTEM.OUT.PRINTLN (Start); String Path= Request.getsession (). Getservletcontext (). Getrealpath ("Upload");//String fileName = File.getoriginalfilename ();String FileName =NewDate (). GetTime () + ". jpg"; SYSTEM.OUT.PRINTLN (path); File TargetFile=NewFile (path, fileName); if(!targetfile.exists ()) {Targetfile.mkdirs (); } //Save Try{File.transferto (targetfile); } Catch(Exception e) {e.printstacktrace (); } model.addattribute ("FileUrl", Request.getcontextpath () + "/upload/" +fileName); return"Uploadresult"; }}
Spring MVC File Upload