最经在工作中要实现文件的无刷新上传,当然XmlHttpRequest对象是无法实现文件的上传功能的。google后找到JQuery的fileupload插件,此插件通过一个IFrame并在IFrame中创建一个form表单来实现文件上传;而在我的应用中还需要带一些其他的文本参数,而此插件并未提供此功能。
既然是动态创建form表单,那么更定能加入其他参数的,请看代码(注意第41行):
jQuery.extend({
createUploadIframe:function(id,uri)
{
//createframe
varframeId='jUploadFrame'+id;
if(window.ActiveXObject){
vario=document.createElement('<iframeid="'+frameId+'"name="'+frameId+'"/>');
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
},
createUploadForm:function(id,fileElementId,data)
{
//createform
varformId='jUploadForm'+id;
varfileId='jUploadFile'+id;
varform=$('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');
varoldElement=$('#'+fileElementId);
varnewElement=$(oldElement).clone();
$(oldElement).attr('id',fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
if(data){
for(variindata){
$('<inputtype="hidden"name="'+i+'"value="'+data[i]+'"/>').appendTo(form);
}
}
//setattributes
$(form).css('position','absolute');
$(form).css('top','-1200px');
$(form).css('left','-1200px');
$(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,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;
//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",s]);
}else
jQuery.handleError(s,status);
}catch(e)
{
status="error";
jQuery.handleError(s,status,e);
}
//Therequestwascompleted
if(s.global)
jQuery.event.trigger("ajaxComplete",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
{
$(io).remove();
$(form).remove();
}catch(e)
{
jQuery.handleError(s,e);
}
},100)
xml=null
}
}
//Timeoutchecker
if(s.timeout>0)
{
setTimeout(function(){
//Checktoseeiftherequestisstillhappening
if(!requestDone)uploadCallback("timeout");
},s.timeout);
}
try
{
//vario=$('#'+frameId);
varform=$('#'+formId);
$(form).attr('action',s.url);
$(form).attr('method','POST');
$(form).attr('target',frameId);
if(form.encoding)
{
form.encoding='multipart/form-data';
}
else
{
form.enctype='multipart/form-data';
}
$(form).submit();
}catch(e)
{
jQuery.handleError(s,e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload',uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load',uploadCallback,false);
}
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);
//evaluatescriptswithinhtml
if(type=="html")
jQuery("<div>").html(data).evalScripts();
//alert($('param',data).each(function(){alert($(this).attr('value'));}));
returndata;
}
})
使用方法:
$.ajaxFileUpload({
url:'/ajax/mine/uploadlogo',
secureuri:false,
fileElementId:'input_logo',
dataType:'json',
data:{//加入的文本参数
"logoPath":"param1",
"logoName":"param2"
},
success:function(data){
},
error:function(){
showError("上传失败,请检查文件是否符合格式要求。");
}
});
最后注意服务器返回的responsetype必须是text/html