SPRINGMVC steps to implement file uploads:
1. On the page, by using input to prepare the file component, the label must be given the Name property value and require that the form form must be given a property: Enctype= "Multipart/form-data" 2. In the Pom.xml file, add a third-party tool for file uploads: Commons-fileupload-1.3.2. jarcommons-io-2.2. Jar3. In app- Springmvc.xml configuration file, the object to prepare the upload operation: Commonsmultipartresolver in this object, we can set the file size, encoding method, etc. 4. In the controller, by @requestparam multipartfile pic This way, to receive page-passed files here, the name of the parameter must be the same as the Name property value of the file component on the page at this time, in the controller, has been able to properly receive the page uploaded files, the next step, Just save the file you received to the server's hard drive .
<!--2 File upload dependent- <dependency> <groupId>commons-fileupload</groupId> < artifactid>commons-fileupload</artifactid> <version>1.3.2</version> </ Dependency>
class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name= " Maxuploadsizeperfile "value=" 102400000 "></property> </bean>
Controller:
<!--4 Controller ... File Upload--@RequestMapping (Value= "AddFile", method=requestmethod.post) Publicstring AddFile (@RequestParam multipartfile pic,httpservletrequest Request,model Model) {string filename=Pic.getoriginalfilename (); System.out.println ("The name of the received file:" +filename); String ContentType=Pic.getcontenttype (); System.out.println ("Type of received file:" +ContentType); InputStream IStream=NULL; OutputStream OStream=NULL; String Realpath= Request.getsession (). Getservletcontext (). Getrealpath ("/imgs"); //get a random stringString string =Uuid.randomuuid (). toString (); String Endname= Filename.substring (Filename.lastindexof (".")), Filename.length ()); /*try {is = Pic.getinputstream (); OS = new FileOutputStream (New File (realpath+ "/" +uuid+endname)); To output a file to a hard disk, the first way: write the throttle yourself and finish the output by reading the side-by-side write operation byte [] b = new byte[1024]; int len = Is.read (b); while (len!=-1) {os.write (b, 0, Len); Len = Is.read (b); } os.flush (); Os.close (); Is.close (); } catch (IOException e) {e.printstacktrace (); }*/ //complete the copy with the tools provided by the Commons-io package Try{IStream=Pic.getinputstream (); OStream=NewFileOutputStream (NewFile (realpath+ "/" +string+endname)); Filecopyutils.copy (IStream, OStream); Ostream.flush (); Ostream.close (); Istream.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("File Save path:" +realpath+ "/" +string+endname+ "...."); return"Index"; }
File upload under SSM framework