志在指尖
用双手敲打未来

ajaxfileupload(上传用法)

ajaxfileupload

首先要引进两个js
注意次序
$(function(){
$(‘#upload’).click(function(){
$(“#submit_info”).click(
function(){
varfileObj=document.getElementById(“file_e”).files;
if(fileObj.length<1){
alert(“请选择一个上传文件!”);
}else{
ajaxFileUpload();
}
})
});
});
functionajaxFileUpload(){
$.ajaxFileUpload(
{
url:’/student/openUpload/’,
type:’post’,
secureuri:false,//是否需要安全协议,一般设置为false
fileElementId:’file_e’,//文件上传域的ID
dataType:’json’,//返回值类型一般设置为json
success:function(response){//处理完数据后前台的回调函数(即后台执行完之后前台接着要做的事)
if(response[‘flag’]==true){
vardata=response[‘msg’];
alert(data);
window.location=”/student/open/”
}else{
data=response[‘msg’];
alert(data);
}
},
error:function(data,status,e)//服务器呼应失利处理函数
{
alert(e);
}
});
}aja

ajaxfileupload上传用法

1.根据一般按钮完成文件上传
基本思路:使用隐藏file域,经过触发change事情完成ajax文件上传
前端页面(根据vue.js)
js代码
varvm=newVue({
methods:{
selectCover:function(){
$(‘#cover’).trigger(‘click’);
},
uploadCover:function(){
if(checkFileExt($(‘#cover’).val(),[‘jpg’,’png’])){
$.ajaxFileUpload({
url:’../../test/upload’,
type:’post’,
fileElementId:[‘cover’],
dataType:’json’,
success:function(data,status){
if(data.code==’0′){
dialogMsg(data.msg,’success’);
}else{
dialogMsg(data.msg,’error’);
}
},
error:function(data,status,e){
dialogMsg(e,’error’)
}
});
}else{
dialogMsg(‘仅支撑jpg,png类型!’);
}
$(‘#cover’).on(‘change’,vm.uploadCover);
}
}
})
后台代码(根据springmvc)
1.Controller
@RequestMapping(“/cover/upload”)
publicRuploadTemplateCover(HttpServletRequestrequest){
StringtemplateId=UUID.randomUUID().toString();
StringtemplatePath=”/upload/template/”+templateId+”/”;
booleansuccess=UploadUtils.uploadFile(request,templatePath,”cover”);
if(success){
returnR.ok(“上传封面成功!”).put(“templateId”,templateId).put(“path”,templatePath);
}
returnR.error(“上传文件失利!”);
}
2.UploadUtil
publicstaticbooleanuploadFile(HttpServletRequestrequest,StringfilePath,StringfileName){
CommonsMultipartResolvermultipartResolver=newCommonsMultipartResolver(
request.getSession().getServletContext());
if(multipartResolver.isMultipart(request)){
MultipartHttpServletRequestmultiRequest=(MultipartHttpServletRequest)request;
StringpathDir=getUploadDir(request,filePath);
FiledirFile=newFile(pathDir);
if(!dirFile.isDirectory()){
dirFile.mkdirs();
}
MultipartFilemultipartFile=multiRequest.getFile(“file”);
if(multipartFile!=null){
Stringname=multipartFile.getOriginalFilename();
StringpostFix=name.substring(name.lastIndexOf(“.”)).toLowerCase();
StringsaveName=fileName+postFix;
StringsavePath=pathDir+File.separator+saveName;
Filefile=newFile(savePath);
file.setWritable(true,false);
try{
multipartFile.transferTo(file);
returntrue;
}catch(Exceptione){
LOG.error(name+”保存失利”,e);
}
}}
returnfalse;
}
publicstaticStringgetUploadDir(HttpServletRequestrequest,Stringpath){
returnrequest.getServletContext().getRealPath(path);
}
2.解决文件类型判断
js方法,具体调用示例见上节
checkFileExt=function(fileName,fileExts){
varcheck=false;
varindex=fileName.lastIndexOf(“.”);
varext=fileName.substr(index+1);
for(vari=0;i
if(ext==fileExts[i]){
check=true;
break;
}
}
returncheck;
}
3.file域change函数只执行一次
问题:ajaxFileUpload插件会把原来的file元素替换成新的file元素,导致之前绑定的change事情失效
解决办法:在调用逻辑结束后从头绑定change事情
4.ajaxfileupload.js
jQuery.extend({
createUploadIframe:function(id,uri){
//createframe
varframeId=’jUploadFrame’+id;
variframeHtml=’
if(window.ActiveXObject){
if(typeofuri==’boolean’){
iframeHtml+=’src=”‘+’javascript:false’+'”‘;
}
elseif(typeofuri==’string’){
iframeHtml+=’src=”‘+uri+'”‘;
}
}
iframeHtml+=’/>’;
jQuery(iframeHtml).appendTo(document.body);
returnjQuery(‘#’+frameId).get(0);
},
createUploadForm:function(id,fileElementId,data,fileElement){
//createform
varformId=’jUploadForm’+id;
varfileId=’jUploadFile’+id;
varform=jQuery(‘
‘);
if(data){
for(variindata){
jQuery(”).appendTo(form);
}
}
if(typeof(fileElementId)==’string’){
fileElementId=[fileElementId];
}
for(variinfileElementId){
varoldElement=jQuery(‘#’+fileElementId[i]);
varnewElement=jQuery(oldElement).clone(true,true);
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
s=jQuery.extend({},jQuery.ajaxSettings,s);
varid=newDate().getTime()
varform=jQuery.createUploadForm(id,s.fileElementId,(typeof(s.data)==’undefined’?false:s.data),s.fileElement);
vario=jQuery.createUploadIframe(id,s.secureuri);
varframeId=’jUploadFrame’+id;
varformId=’jUploadForm’+id;
//Watchforanewsetofrequests
if(s.global&&!jQuery.active++){
jQuery.event.trigger(“ajaxStart”);
}
varrequestDone=false;
//Createtherequestobject
varxml={}
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]);
}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
if(s.complete)
s.complete(xml,status);
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(){
try{
jQuery(‘#’+frameId).remove();
jQuery(form).remove();
}
catch(e){}
}
};
},
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”){
data=r.responseText;
varstart=data.indexOf(“>”);
if(start!=-1){
varend=data.indexOf(”
if(end!=-1){
data=data.substring(start+1,end);
}
}
eval(“data=”+data);
}
//evaluatescriptswithinhtml
if(type==”html”)
jQuery(”
“).html(data).evalScripts();
returndata;
},
handleError:function(s,xml,status,e){
//Ifalocalcallbackwasspecified,fireit
if(s.error)
s.error(xml,status,e);
//Firetheglobalcallback
if(s.global)
jQuery.event.trigger(“ajaxError”,[xml,s,e]);
}
});

未经允许不得转载:IT技术网站 » ajaxfileupload(上传用法)
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载