Introducing JS
<th:src= "@{/js/ajaxfileupload.js}"></script>
Html
<TR> <TD>Attachment:</TD> <TD> <inputtype= "hidden"ID= "Insertcyefuji"name= "Fuji" /> <inputtype= "File"ID= "Uploadcyefuji"name= "File" /> </TD></TR>
JS code-----Automatically upload when you finish selecting files
$ (' input[id= ' Uploadcyefuji "]). Change (function (e) { var formData = new FormData (); Formdata.append (' file ', $ (' #uploadcyefuji ') [0].files[0]); $.ajax ({ URL: '/fileupload ', type: ' POST ', cache:false, data:formdata, Processdata:false, contenttype:false }). Done (function (res) { alert ("Upload succeeded") }). Fail (function (res) { alert ("Upload failed"); })
Controller Backend Code
1 /**2 * Implement file Upload3 * @throwsIOException4 * @throwsillegalstateexception5 * */6@RequestMapping (value= "FileUpload", method =requestmethod.post)7 @ResponseBody8 PublicString fileUpload (httpservletrequest req,multipartfile file)throwsillegalstateexception, ioexception{9 if(File.getoriginalfilename () = =NULL|| File.getoriginalfilename (). Equals ("")){TenSystem.err.println ("Empty ++++"); One return""; A}Else{ -String Picname =Uuid.randomuuid (). toString (); - //Get file name theString Oriname =file.getoriginalfilename (); -System.err.println (oriname+ "Picture name"); - //get picture suffix -String extname = oriname.substring (Oriname.lastindexof ("."))); +System.err.println ("suffix name" +extname); - if(Extname.equals (". jpg") | | extname.equals (". JPG ") | | Extname.equals (". png") | | Extname.equals (". PNG ")){ +String path = Req.getsession (). Getservletcontext (). Getrealpath ("/"); ASystem.out.println ("path=" +path); at -File.transferto (NewFile (path+ "upload/" +picname +extname)); - //user.setusername (picname + extname); - //M.addattribute ("FileName" +count, Picname + extname); - //count--; - //list.add (user); in - //set the picture name to the product toSystem.err.println ("Upload picture complete"); + return"Upload succeeded"; -}Else { theSYSTEM.ERR.PRINTLN ("Not formatted"); * return"Not formatted"; $ Panax Notoginseng } - } the}
Springmvc_ajax uploading files asynchronously (based on ajaxfileupload.js)