Package Controller;import Java.io.file;import Java.io.ioexception;import javax.servlet.http.HttpServletRequest; Import Org.apache.commons.lang.xwork.randomstringutils;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.servlet.ModelAndView; Import Pojo. Uploadedimagefile; The second parameter of the @Controllerpublic class Uploadcontroller {@RequestMapping ("/uploadimage")//Method Uploa Dedimagefile has been injected with the image public Modelandview upload (httpservletrequest request, uploadedimagefile file) th Rows IllegalStateException, IOException {//via Randomstringutils.randomalphanumeric (10); Get a random file name. Because the user may upload files of the same file name, in order not to overwrite the original file, a random file name method to circumvent String name = Randomstringutils.randomalphanumeric (10); String NewFileName = name + ". jpg"; Request.getservletcontext (). Getrealpath ("/image")//According to Request.getservletcontext (). Getrealpath get to the web directory Image directory, which is used to store the uploadedFile. File NewFile = new file (Request.getservletcontext (). Getrealpath ("/image"), NewFileName); System.out.println (NewFile); System.out.println (Newfile.getparentfile ()); Newfile.getparentfile (). Mkdirs (); Call File.getimage (). TransferTo (NewFile); Copy file File.getimage (). TransferTo (NewFile); Modelandview Mav = new Modelandview ("Showuploadedfile"); Mav.addobject ("ImageName", NewFileName); return MAV; }}
The above 2 output statements are printed as follows
信息: Starting ProtocolHandler ["http-bio-8080"]六月 01, 2018 5:12:52 下午 org.apache.coyote.AbstractProtocol start信息: Starting ProtocolHandler ["ajp-bio-8009"]六月 01, 2018 5:12:52 下午 org.apache.catalina.startup.Catalina start信息: Server startup in 4227 msC:\Users\chen\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\springmvc\image\x6Cf5WOFyZ.jpgC:\Users\chen\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\springmvc\image
New class Uploadcontroller as upload controller
Preparation method upload Map upload path/uploadimage
- The second parameter of the Uploadedimagefile method has been injected with the image
- by Randomstringutils.randomalphanumeric (10); Gets a random file name. Because the user may upload files of the same file name, in order not to overwrite the original file, through the random file name method to circumvent
- According to Request.getservletcontext (). Getrealpath Gets the image directory under the WebContent directory, which is used to store the uploaded file.
- Call File.getimage (). TransferTo (NewFile); Copying files
- Submits the generated random file name to the view for subsequent display
Springmvc Uploading Images