SpringMVC结合ajaxfileupload实现文件无刷新上传代码
jQuery没有提供ajax的文件上传,我们可以通过ajaxfileupload实现ajax文件的上传。其实ajaxfileupload文件上传特别的简单。下面就演示一下在SpringMVC中实现ajax的文件上传。
1、后台接收代码
首先在spring的配置文件中添加文件上传配置
再写文件接收的代码
packagecom.chinaunicom.jlmssp.controller; importjava.io.File; importjava.io.IOException; importjava.util.Arrays; importjava.util.Date; importjava.util.HashMap; importjavax.servlet.ServletContext; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; importorg.apache.commons.fileupload.servlet.ServletFileUpload; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.ui.Model; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.ResponseBody; importorg.springframework.web.multipart.commons.CommonsMultipartFile; importcom.chinaunicom.jlmssp.model.DataResponse; importcom.chinaunicom.jlmssp.model.JavaToJsMsg; importcom.chinaunicom.jlmssp.model.Org_UserInfo; importcom.chinaunicom.jlmssp.model.Repaly_Expert_Home_Page; importcom.chinaunicom.jlmssp.services.Replay_ExpertManageService; /** *项目复制管理子系统 *专家云管理 *@authorSunYue *@version0.1 */ @Controller @RequestMapping("/admin/Replay_ExpertManageController.do") publicclassReplay_ExpertManageController{ privatestaticfinalHashMapTypeMap=newHashMap (); static{ TypeMap.put("image","gif,jpg,jpeg,png,bmp"); TypeMap.put("flash","swf,flv"); TypeMap.put("media","swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); TypeMap.put("file","doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf"); } @Autowired Replay_ExpertManageServicereplayExpertManageService; /** *@authorsunyue *@date2017年2月28日下午12:49:33 *@Description:图片上传方法 *@returnmessage:-1没有文件上传0上传成功1上传失败2文件超过上传大小3文件格式错误4上传文件路径非法5上传目录没有写权限 *@returnvoid返回类型 */ @RequestMapping(params="op=getImageUpload",method=RequestMethod.POST) publicvoidgetImageUpload(@RequestParam("upload")CommonsMultipartFilefile,HttpServletRequestrequest, HttpServletResponseresponse){ if(!file.isEmpty()){ /*ServletContextservletContext=request.getSession() .getServletContext(); StringuploadPath=servletContext.getRealPath("/") +"images\\replay-expert\\"; StringupPathString=request.getServletPath();*/ //获取项目工作空间下工程路径的方法,将图片保存到工程路径下 Stringt=Thread.currentThread().getContextClassLoader().getResource("").getPath(); intnum=t.indexOf(".metadata"); StringuploadPath=t.substring(1,num).replace('/','\\')+"jl_mssp_V3_0\\WebContent\\images\\replay-expert\\"; //文件上传大小 longfileSize=3*1024*1024; if(file.getSize()>fileSize){ backInfo(response,false,2,""); return; } StringOriginalFilename=file.getOriginalFilename(); StringfileSuffix=OriginalFilename.substring( OriginalFilename.lastIndexOf(".")+1).toLowerCase(); if(!Arrays.asList(TypeMap.get("image").split(",")).contains( fileSuffix)){ backInfo(response,false,3,""); return; } if(!ServletFileUpload.isMultipartContent(request)){ backInfo(response,false,-1,""); return; } //检查上传文件的目录 FileuploadDir=newFile(uploadPath); if(!uploadDir.isDirectory()){ if(!uploadDir.mkdir()){ backInfo(response,false,4,""); return; } } //是否有上传的权限 if(!uploadDir.canWrite()){ backInfo(response,false,5,""); return; } //新文件名 Stringnewname=""; /*if(null!=filePre){ newname+=filePre;//对应模块上传的文件名前缀 }*/ newname+="test1111"+"."+fileSuffix; FilesaveFile=newFile(uploadPath,newname); try{ file.transferTo(saveFile); backInfo(response,true,0,newname); }catch(Exceptione){ //LOG.error(e.getMessage(),e); backInfo(response,false,1,""); return; } }else{ backInfo(response,false,-1,""); return; } } //返回信息 privatevoidbackInfo(HttpServletResponseresponse,booleanflag,intmessage, StringfileName){ Stringjson=""; if(flag){ json="{\"status\":\"success"; }else{ json="{\"status\":\"error"; } json+="\",\"fileName\":\""+fileName+"\",\"message\":\""+message+"\"}"; try{ response.setContentType("text/html;charset=utf-8"); response.getWriter().write(json); }catch(IOExceptione){ //LOG.error(e.getMessage(),e); } } }
2、前台接受代码
使用ajaxfileupload时,首先下载ajaxfileupload文件,导入对应的js文件
文件传输字段必须为file类型,如下:
其次,处理上传文件:
functionajaxFileUpload(){ $.ajaxFileUpload({ type:"POST", async:false, data:{"op":'getImageUpload'}, url:"Replay_ExpertManageController.do", dataType:'json', secureuri:false, fileElementId:"upload", success:function(data,status){ if(data.status=="success"){ //上传成功 alert("上传照片成功"); } switch(data.message){ //解析上传状态 case"0"://上传成功 break; case"-1"://上传文件不能为空 break; default://上传失败 break; } returnfalse; }/*, error:function(jqXHR,textStatus,errorThrown){ //弹出jqXHR对象的信息 alert(jqXHR.responseText); //alert(jqXHR.status); //alert(jqXHR.readyState); //alert(jqXHR.statusText); //弹出其他两个参数的信息 //alert(textStatus); alert(errorThrown); returnfalse; }*/ }); }
三、由于网上的ajaxuploadfile文件都是高版本的,这里将改版完全版文件传上,自己使用
jQuery.extend({ handleError:function(s,xhr,status,e){ //Ifalocalcallbackwasspecified,fireit if(s.error){ s.error.call(s.context||s,xhr,status,e); } //Firetheglobalcallback if(s.global){ (s.context?jQuery(s.context):jQuery.event).trigger("ajaxError",[xhr,s,e]); } }, createUploadIframe:function(id,uri) { varframeId='jUploadFrame'+id; if(window.ActiveXObject){ if(jQuery.browser.version=="9.0") { io=document.createElement('iframe'); io.id=frameId; io.name=frameId; } elseif(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0") { vario=document.createElement(''); if(typeofuri=='boolean'){ io.src='javascript:false'; } elseif(typeofuri=='string'){ io.src=uri; } } } else{ vario=document.createElement('iframe'); io.id=frameId; io.name=frameId; } io.style.position='absolute'; io.style.top='-1000px'; io.style.left='-1000px'; document.body.appendChild(io); returnio; }, ajaxUpload:function(s,xml){ //if((fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0].name))) varuid=newDate().getTime(),idIO='jUploadFrame'+uid,_this=this; varjIO=$(' ').appendTo('body'); varjForm=$(' ').appendTo('body'); varoldElement=$('#'+s.fileElementId); varnewElement=$(oldElement).clone(); $(oldElement).attr('id','jUploadFile'+uid); $(oldElement).before(newElement); $(oldElement).appendTo(jForm); this.remove=function() { if(_this!==null) { jNewFile.before(jOldFile).remove(); jIO.remove();jForm.remove(); _this=null; } } this.onLoad=function(){ vardata=$(jIO[0].contentWindow.document.body).text(); try{ if(data!=undefined){ data=eval('('+data+')'); try{ if(s.success) s.success(data,status); //Firetheglobalcallback if(s.global) jQuery.event.trigger("ajaxSuccess",[xml,s]); if(s.complete) s.complete(data,status); xml=null; }catch(e) { status="error"; jQuery.handleError(s,xml,status,e); } //Therequestwascompleted if(s.global) jQuery.event.trigger("ajaxComplete",[xml,s]); //HandletheglobalAJAXcounter if(s.global&&!--jQuery.active) jQuery.event.trigger("ajaxStop"); //Processresult } }catch(ex){ alert(ex.message); }; } this.start=function(){jForm.submit();jIO.load(_this.onLoad);}; returnthis; }, createUploadForm:function(id,url,fileElementId,data) { //createform varformId='jUploadForm'+id; varfileId='jUploadFile'+id; varform=jQuery(' '); if(data) { for(variindata) { jQuery(' ').appendTo(form); } } varoldElement=jQuery('#'+fileElementId); varnewElement=jQuery(oldElement).clone(); jQuery(oldElement).attr('id',fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //setattributes jQuery(form).css('position','absolute'); jQuery(form).css('top','-1200px'); jQuery(form).css('left','-1200px'); jQuery(form).appendTo('body'); returnform; }, ajaxFileUpload:function(s){ //TODOintroduceglobalsettings,allowingtheclienttomodifythemforallrequests,notonlytimeout //Createtherequestobject varxml={}; s=jQuery.extend({},jQuery.ajaxSettings,s); if(window.ActiveXObject){ varupload=newjQuery.ajaxUpload(s,xml); upload.start(); }else{ varid=newDate().getTime(); varform=jQuery.createUploadForm(id,s.url,s.fileElementId,(typeof(s.data)=='undefined'?false:s.data)); vario=jQuery.createUploadIframe(id,s.secureuri); varframeId='jUploadFrame'+id; varformId='jUploadForm'+id; //Watchforanewsetofrequests if(s.global&&!jQuery.active++) { jQuery.event.trigger("ajaxStart"); } varrequestDone=false; if(s.global) jQuery.event.trigger("ajaxSend",[xml,s]); //Waitforaresponsetocomeback varuploadCallback=function(isTimeout) { vario=document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }elseif(io.contentDocument) { xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s,xml,null,e); } if(xml||isTimeout=="timeout") { requestDone=true; varstatus; try{ status=isTimeout!="timeout"?"success":"error"; //Makesurethattherequestwassuccessfulornotmodified if(status!="error") { //processthedata(runsthexmlthroughhttpDataregardlessofcallback) vardata=jQuery.uploadHttpData(xml,s.dataType); //Ifalocalcallbackwasspecified,fireitandpassitthedata if(s.success) s.success(data,status); //Firetheglobalcallback if(s.global) jQuery.event.trigger("ajaxSuccess",[xml,s]); if(s.complete) s.complete(data,status); }else jQuery.handleError(s,xml,status); }catch(e) { status="error"; jQuery.handleError(s,xml,status,e); } //Therequestwascompleted if(s.global) jQuery.event.trigger("ajaxComplete",[xml,s]); //HandletheglobalAJAXcounter if(s.global&&!--jQuery.active) jQuery.event.trigger("ajaxStop"); //Processresult jQuery(io).unbind(); setTimeout(function() {try { jQuery(io).remove(); jQuery(form).remove(); }catch(e) { jQuery.handleError(s,xml,null,e); } },100); xml=null; } }; //Timeoutchecker if(s.timeout>0) { setTimeout(function(){ //Checktoseeiftherequestisstillhappening if(!requestDone)uploadCallback("timeout"); },s.timeout); } try { varform=jQuery('#'+formId); jQuery(form).attr('action',s.url); jQuery(form).attr('method','POST'); jQuery(form).attr('target',frameId); if(form.encoding) { jQuery(form).attr('encoding','multipart/form-data'); } else { jQuery(form).attr('enctype','multipart/form-data'); } jQuery(form).submit(); }catch(e) { jQuery.handleError(s,xml,null,e); } jQuery('#'+frameId).load(uploadCallback); return{abort:function(){}}; } }, uploadHttpData:function(r,type){ vardata=!type; data=type=="xml"||data?r.responseXML:r.responseText; //Ifthetypeis"script",evalitinglobalcontext if(type=="script") jQuery.globalEval(data); //GettheJavaScriptobject,ifJSONisused. if(type=="json"){ eval("data="+$(data).html()); } //evaluatescriptswithinhtml if(type=="html") jQuery(" ").html(data).evalScripts(); returndata; } });以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。