Note: The request entity is too large, please modify the size of the Nginx server (Baidu Reference 413 request entity Too Large solution)
Jsp:<input type= "File" style= "height:114px;width:100%;p osition:absolute;opacity:0" name= "File1" id= "File1" >
$(function(){ $("#file1"). Change (function(){ //Create a Formdata object vardata =NewFormData (); //adding data to a Formdata object$.each ($ (' #file1 ') [0].files,function(i, file) {Data.append (' Upload_file ', file); }); $.ajax ({URL:' ${pagecontext.request.contextpath}/uploadimage ', type:' POST ', Data:data, cache:false, ContentType:false,//not missingProcessData:false,//not missingSuccessfunction(data) {//Show Append varImgurl= "/" +data; varshowimg = "<div class= ' Img-item ' >" + "</span>" + "</div>"; $("#addImg"). before (SHOWIMG); //Data Append varinputimg = "<input type= ' hidden ' name= ' postimage ' value= '" + Imgurl + ">"; $("#typeId"). After (INPUTIMG); } }); }); });
Java Background section:
1@RequestMapping (value = "/uploadimage", method =requestmethod.post)2 @ResponseBody3 PublicString Uploadimage (HttpServletRequest request)throwsIOException {4Multiparthttpservletrequest multipartrequest =(multiparthttpservletrequest) request;5Iterator<string> Iterator =multipartrequest.getfilenames ();6String fileName = "";7SimpleDateFormat SDF =NewSimpleDateFormat ("YyyyMMdd");8String dir = "upload/" + Sdf.format (NewDate ()) + "/";9String Realpath = Request.getsession (). Getservletcontext (). Getrealpath ("/");Ten while(Iterator.hasnext ()) { OneMultipartfile Multipartfile =Multipartrequest.getfile (Iterator.next ()); A if(Multipartfile! =NULL){ -STRING fn =multipartfile.getoriginalfilename (); -String suffix = fn.substring (Fn.lastindexof ("."))); theFileName = dir + utils.getrandomstringbylength (6) +suffix; -String Path = Realpath +FileName; -Path = path.replace ("\ \", "/"); -File f =NewFile (path); + if(!F.mkdirs ()) { - F.mkdir (); + } A Multipartfile.transferto (f); at } - } - returnFileName; - } - //the above method needs to use the following method - PublicString Getrandomstringbylength (intlength) { inString base = "abcdefghijklmnopqrstuvwxyz0123456789"; -Random random =NewRandom (); toStringBuffer SB =NewStringBuffer (); + for(inti = 0; i < length; i++) { - intNumber =Random.nextint (Base.length ()); the Sb.append (Base.charat (number)); * } $ returnsb.tostring ();Panax Notoginseng}
Java Web File Upload