Plugin Required: Ajaxfileupload.js Commons-fileupload-1.3.1.jar
Web-side:
<form id="Saveform"Method="Post"Enctype="Multipart/form-data"><label> Advertising Pictures: </label><input type="file"Id="Image1"Name="Image1"data-options="required:true"/> ".. /.. /imgsrc/aaaaaa.jpg"Id="img"Width="100px", height="100px"/> <input type="Button"Id="Sub"Value="Upload"/></form>
<script type="Text/javascript">$ (function () {$ ("#sub"). Click (function () {$.ajaxfileupload ({URL:'upload.do', Secureuri:false, Fileelementid:'Image1',//ID of the file tagDataType:'JSON',//type of return datasuccess:function (data) {$ ("#img"). attr ("src",".. /.. /imgsrc/"+data); }, }); });});</script>
Java background:
@RequestMapping ("Upload") @ResponseBody PublicString Upload (@RequestParam ("Image1") Multipartfile file,httpservletrequest req) {//String Savefilepath = Req.getservletcontext (). Getrealpath ("/web-inf/upload");String savefilepath=Constant.savepath; Try { if(!File.isempty ()) { //get the file name of the pictureString FileName =File.getoriginalfilename (); //get the name extension of a pictureString ExtensionName =fileName. Substring (Filename.lastindexof (".") +1); //new picture file name = Get timestamp + "." Picture extensionString NewFileName = string.valueof (System.currenttimemillis ()) +"."+ExtensionName; Imgutils.savefile (newfilename, file, Savefilepath); returnNewFileName; }Else{ return "Exception"; } } Catch(Exception e) {e.printstacktrace (); return "Exception"; } }
Public Static voidSaveFile (String newfilename, Multipartfile filedata,string savefilepath) {//TODO auto-generated Method Stub//Get server picture storage path based on configuration file /*Build File directory*/File Filedir=NewFile (Savefilepath); if(!filedir.exists ()) {Filedir.mkdirs (); } Try{FileOutputStream out=NewFileOutputStream (Savefilepath +"\\"+newfilename); //Write File out. Write (Filedata.getbytes ()); out. Flush (); out. Close (); } Catch(Exception e) {e.printstacktrace (); } }
Tomcat:
"webapps" autodeploy="true" name=" localhost" unpackwars="true"> <context docbase="D:\upload" path="/imgsrc"/>
Web-side image upload