AjaxUpLoad.js实现文件上传
AjaxUpload.js文件的代码,供大家参考,具体内容如下
/**
*AJAXUpload(http://valums.com/ajax-upload/)
*Copyright(c)AndrisValums
*LicensedundertheMITlicense(http://valums.com/mit-license/)
*ThankstoGaryHaran,DavidMark,CoreyBurnsandothersforcontributions
*/
(function(){
/*globalwindow*/
/*jslintbrowser:true,devel:true,undef:true,nomen:true,bitwise:true,regexp:true,newcap:true,immed:true*/
/**
*WrapperforFireBug'sconsole.log
*/
functionlog(){
if(typeof(console)!='undefined'&&typeof(console.log)=='function'){
Array.prototype.unshift.call(arguments,'[AjaxUpload]');
console.log(Array.prototype.join.call(arguments,''));
}
}
/**
*Attacheseventtoadomelement.
*@param{Element}el
*@paramtypeeventname
*@paramfncallbackThisreferstothepassedelement
*/
functionaddEvent(el,type,fn){
if(el.addEventListener){
el.addEventListener(type,fn,false);
}elseif(el.attachEvent){
el.attachEvent('on'+type,function(){
fn.call(el);
});
}else{
thrownewError('notsupportedorDOMnotloaded');
}
}
/**
*Attachesresizeeventtoawindow,limiting
*numberofeventfired.Firesonlywhenencounteres
*delayof100afterseriesofevents.
*
*Somebrowsersfireeventmultipletimeswhenresizing
*http://www.quirksmode.org/dom/events/resize.html
*
*@paramfncallbackThisreferstothepassedelement
*/
functionaddResizeEvent(fn){
vartimeout;
addEvent(window,'resize',function(){
if(timeout){
clearTimeout(timeout);
}
timeout=setTimeout(fn,100);
});
}
//Needsmoretesting,willberewritenfornextversion
//getOffsetfunctioncopiedfromjQuerylib(http://jquery.com/)
if(document.documentElement.getBoundingClientRect){
//GetOffsetusinggetBoundingClientRect
//http://ejohn.org/blog/getboundingclientrect-is-awesome/
vargetOffset=function(el){
varbox=el.getBoundingClientRect();
vardoc=el.ownerDocument;
varbody=doc.body;
vardocElem=doc.documentElement;//forie
varclientTop=docElem.clientTop||body.clientTop||0;
varclientLeft=docElem.clientLeft||body.clientLeft||0;
//InInternetExplorer7getBoundingClientRectpropertyistreatedasphysical,
//whileothersarelogical.Makealllogical,likeinIE8.
varzoom=1;
if(body.getBoundingClientRect){
varbound=body.getBoundingClientRect();
zoom=(bound.right-bound.left)/body.clientWidth;
}
if(zoom>1){
clientTop=0;
clientLeft=0;
}
vartop=box.top/zoom+(window.pageYOffset||docElem&&docElem.scrollTop/zoom||body.scrollTop/zoom)-clientTop,
left=box.left/zoom+(window.pageXOffset||docElem&&docElem.scrollLeft/zoom||body.scrollLeft/zoom)-clientLeft;
return{
top:top,
left:left
};
};
}else{
//Getoffsetaddingalloffsets
vargetOffset=function(el){
vartop=0,
left=0;
do{
top+=el.offsetTop||0;
left+=el.offsetLeft||0;
el=el.offsetParent;
}while(el);
return{
left:left,
top:top
};
};
}
/**
*Returnsleft,top,rightandbottompropertiesdescribingtheborder-box,
*inpixels,withthetop-leftrelativetothebody
*@param{Element}el
*@return{Object}Containsleft,top,right,bottom
*/
functiongetBox(el){
varleft,right,top,bottom;
varoffset=getOffset(el);
left=offset.left;
top=offset.top;
right=left+el.offsetWidth;
bottom=top+el.offsetHeight;
return{
left:left,
right:right,
top:top,
bottom:bottom
};
}
/**
*Helperthattakesobjectliteral
*andaddallpropertiestoelement.style
*@param{Element}el
*@param{Object}styles
*/
functionaddStyles(el,styles){
for(varnameinstyles){
if(styles.hasOwnProperty(name)){
el.style[name]=styles[name];
}
}
}
/**
*Functionplacesanabsolutelypositioned
*elementontopofthespecifiedelement
*copyingpositionanddimentions.
*@param{Element}from
*@param{Element}to
*/
functioncopyLayout(from,to){
varbox=getBox(from);
addStyles(to,{
position:'absolute',
left:box.left+'px',
top:box.top+'px',
width:from.offsetWidth+'px',
height:from.offsetHeight+'px'
});
}
/**
*Createsandreturnselementfromhtmlchunk
*UsesinnerHTMLtocreateanelement
*/
vartoElement=(function(){
vardiv=document.createElement('div');
returnfunction(html){
div.innerHTML=html;
varel=div.firstChild;
returndiv.removeChild(el);
};
})();
/**
*Functiongeneratesuniqueid
*@returnuniqueid
*/
vargetUID=(function(){
varid=0;
returnfunction(){
return'ValumsAjaxUpload'+id++;
};
})();
/**
*Getfilenamefrompath
*@param{String}filepathtofile
*@returnfilename
*/
functionfileFromPath(file){
returnfile.replace(/.*(\/|\\)/,"");
}
/**
*Getfileextensionlowercase
*@param{String}filename
*@returnfileextenstion
*/
functiongetExt(file){
return(-1!==file.indexOf('.'))?file.replace(/.*[.]/,''):'';
}
functionhasClass(el,name){
varre=newRegExp('\\b'+name+'\\b');
returnre.test(el.className);
}
functionaddClass(el,name){
if(!hasClass(el,name)){
el.className+=''+name;
}
}
functionremoveClass(el,name){
varre=newRegExp('\\b'+name+'\\b');
el.className=el.className.replace(re,'');
}
functionremoveNode(el){
el.parentNode.removeChild(el);
}
/**
*Easystylinganduploading
*@constructor
*@parambuttonAnelementyouwantconvertto
*uploadbutton.Testeddimentionsupto500x500px
*@param{Object}optionsSeedefaultsbelow.
*/
window.AjaxUpload=function(button,options){
this._settings={
//Locationoftheserver-sideuploadscript
action:'upload.php',
//Fileuploadname
name:'userfile',
//Additionaldatatosend
data:{},
//Submitfileassoonasit'sselected
autoSubmit:true,
//Thetypeofdatathatyou'reexpectingbackfromtheserver.
//htmlandxmlaredetectedautomatically.
//Onlyusefulwhenyouareusingjsondataasaresponse.
//Setto"json"inthatcase.
responseType:false,
//Classappliedtobuttonwhenmouseishovered
hoverClass:'hover',
//ClassappliedtobuttonwhenAUisdisabled
disabledClass:'disabled',
//Whenuserselectsafile,usefulwithautoSubmitdisabled
//Youcanreturnfalsetocancelupload
onChange:function(file,extension){},
//Callbacktofirebeforefileisuploaded
//Youcanreturnfalsetocancelupload
onSubmit:function(file,extension){},
//Firedwhenfileuploadiscompleted
//WARNING!DONOTUSE"FALSE"STRINGASARESPONSE!
onComplete:function(file,response){}
};
//Mergetheusersoptionswithourdefaults
for(variinoptions){
if(options.hasOwnProperty(i)){
this._settings[i]=options[i];
}
}
//buttonisn'tnecessaryadomelement
if(button.jquery){
//jQueryobjectwaspassed
button=button[0];
}elseif(typeofbutton=="string"){
if(/^#.*/.test(button)){
//IfjQueryuserpasses#elementIddon'tbreakit
button=button.slice(1);
}
button=document.getElementById(button);
}
if(!button||button.nodeType!==1){
thrownewError("Pleasemakesurethatyou'repassingavalidelement");
}
if(button.nodeName.toUpperCase()=='A'){
//disablelink
addEvent(button,'click',function(e){
if(e&&e.preventDefault){
e.preventDefault();
}elseif(window.event){
window.event.returnValue=false;
}
});
}
//DOMelement
this._button=button;
//DOMelement
this._input=null;
//Ifdisabledclickingonbuttonwon'tdoanything
this._disabled=false;
//ifthebuttonwasdisabledbeforerefreshifwillremain
//disabledinFireFox,let'sfixit
this.enable();
this._rerouteClicks();
};
//assigningmethodstoourclass
AjaxUpload.prototype={
setData:function(data){
this._settings.data=data;
},
disable:function(){
addClass(this._button,this._settings.disabledClass);
this._disabled=true;
varnodeName=this._button.nodeName.toUpperCase();
if(nodeName=='INPUT'||nodeName=='BUTTON'){
this._button.setAttribute('disabled','disabled');
}
//hideinput
if(this._input){
//WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
//Theproblemisthatthevalueofinputdoesn'tchangeifit
//hasdisplaynonewhenuserselectsafile
this._input.parentNode.style.visibility='hidden';
}
},
enable:function(){
removeClass(this._button,this._settings.disabledClass);
this._button.removeAttribute('disabled');
this._disabled=false;
},
/**
*Createsinvisiblefileinput
*thatwillhoverabovethebutton
*
*/
_createInput:function(){
varself=this;
varinput=document.createElement("input");
input.setAttribute('type','file');
input.setAttribute('name',this._settings.name);
addStyles(input,{
'position':'absolute',
//inOperaonly'browse'button
//isclickableanditislocatedat
//therightsideoftheinput
'right':0,
'margin':0,
'padding':0,
'fontSize':'480px',
'cursor':'pointer'
});
vardiv=document.createElement("div");
addStyles(div,{
'display':'block',
'position':'absolute',
'overflow':'hidden',
'margin':0,
'padding':0,
'opacity':0,
//Makesurebrowsebuttonisintherightside
//inInternetExplorer
'direction':'ltr',
//MaxzIndexsupportedbyOpera9.0-9.2
'zIndex':2147483583
});
//Makesurethatelementopacityexists.
//OtherwiseuseIEfilter
if(div.style.opacity!=="0"){
if(typeof(div.filters)=='undefined'){
thrownewError('Opacitynotsupportedbythebrowser');
}
div.style.filter="alpha(opacity=0)";
}
addEvent(input,'change',function(){
if(!input||input.value===''){
return;
}
//Getfilenamefrominput,required
//assomebrowsershavepathinsteadofit
varfile=fileFromPath(input.value);
if(false===self._settings.onChange.call(self,file,getExt(file))){
self._clearInput();
return;
}
//Submitformwhenvalueischanged
if(self._settings.autoSubmit){
self.submit();
}
});
addEvent(input,'mouseover',function(){
addClass(self._button,self._settings.hoverClass);
});
addEvent(input,'mouseout',function(){
removeClass(self._button,self._settings.hoverClass);
//WeusevisibilityinsteadofdisplaytofixproblemwithSafari4
//Theproblemisthatthevalueofinputdoesn'tchangeifit
//hasdisplaynonewhenuserselectsafile
input.parentNode.style.visibility='hidden';
});
div.appendChild(input);
document.body.appendChild(div);
this._input=input;
},
_clearInput:function(){
if(!this._input){
return;
}
//this._input.value='';Doesn'tworkinIE6
removeNode(this._input.parentNode);
this._input=null;
this._createInput();
removeClass(this._button,this._settings.hoverClass);
},
/**
*Functionmakessurethatwhenuserclicksuploadbutton,
*thethis._inputisclickedinstead
*/
_rerouteClicks:function(){
varself=this;
//IEwilllaterdisplay'accessdenied'error
//ifyouuseusingself._input.click()
//otherbrowsersjustignoreclick()
addEvent(self._button,'mouseover',function(){
if(self._disabled){
return;
}
if(!self._input){
self._createInput();
}
vardiv=self._input.parentNode;
copyLayout(self._button,div);
div.style.visibility='visible';
});
//commentedbecausewenowhideinputonmouseleave
/**
*Whenthewindowisresizedtheelements
*canbemisalignedifbuttonpositiondepends
*onwindowsize
*/
//addResizeEvent(function(){
//if(self._input){
//copyLayout(self._button,self._input.parentNode);
//}
//});
},
/**
*Createsiframewithuniquename
*@return{Element}iframe
*/
_createIframe:function(){
//Wecan'tusegetTime,becauseitsometimesreturn
//samevalueinsafari:(
varid=getUID();
//Wecan'tusefollowingcodeasthenameattribute
//won'tbeproperlyregisteredinIE6,andnewwindow
//onformsubmitwillopen
//variframe=document.createElement('iframe');
//iframe.setAttribute('name',id);
variframe=toElement(' ');
//src="javascript:false;wasadded
//becauseitpossiblyremovesie6prompt
//"Thispagecontainsbothsecureandnonsecureitems"
//Anyway,itdoesn'tdoanyharm.
iframe.setAttribute('id',id);
iframe.style.display='none';
document.body.appendChild(iframe);
returniframe;
},
/**
*Createsform,thatwillbesubmittedtoiframe
*@param{Element}iframeWheretosubmit
*@return{Element}form
*/
_createForm:function(iframe){
varsettings=this._settings;
//Wecan'tusethefollowingcodeinIE6
//varform=document.createElement('form');
//form.setAttribute('method','post');
//form.setAttribute('enctype','multipart/form-data');
//Becauseinthiscasefilewon'tbeattachedtorequest
varform=toElement('');
form.setAttribute('action',settings.action);
form.setAttribute('target',iframe.name);
form.style.display='none';
document.body.appendChild(form);
//Createhiddeninputelementforeachdatakey
for(varpropinsettings.data){
if(settings.data.hasOwnProperty(prop)){
varel=document.createElement("input");
el.setAttribute('type','hidden');
el.setAttribute('name',prop);
el.setAttribute('value',settings.data[prop]);
form.appendChild(el);
}
}
returnform;
},
/**
*GetsresponsefromiframeandfiresonCompleteeventwhenready
*@paramiframe
*@paramfileFilenametouseinonCompletecallback
*/
_getResponse:function(iframe,file){
//gettingresponse
vartoDeleteFlag=false,
self=this,
settings=this._settings;
addEvent(iframe,'load',function(){
if(//ForSafari
iframe.src=="javascript:'%3Chtml%3E%3C/html%3E';"||
//ForFF,IE
iframe.src=="javascript:'';"){
//Firsttimearound,donotdelete.
//Wereloadtoblankpage,sothatreloadingmainpage
//doesnotre-submitthepost.
if(toDeleteFlag){
//FixbusystateinFF3
setTimeout(function(){
removeNode(iframe);
},
0);
}
return;
}
vardoc=iframe.contentDocument?iframe.contentDocument:window.frames[iframe.id].document;
//fixingOpera9.26,10.00
if(doc.readyState&&doc.readyState!='complete'){
//Operafiresloadeventmultipletimes
//EvenwhentheDOMisnotreadyyet
//thisfixshouldnotaffectotherbrowsers
return;
}
//fixingOpera9.64
if(doc.body&&doc.body.innerHTML=="false"){
//InOpera9.64eventwasfiredsecondtime
//whenbody.innerHTMLchangedfromfalse
//toserverresponseapprox.after1sec
return;
}
varresponse;
if(doc.XMLDocument){
//responseisaxmldocumentInternetExplorerproperty
response=doc.XMLDocument;
}elseif(doc.body){
//responseishtmldocumentorplaintext
response=doc.body.innerHTML;
if(settings.responseType&&settings.responseType.toLowerCase()=='json'){
//Ifthedocumentwassentas'application/javascript'or
//'text/javascript',thenthebrowserwrapsthetextina
//tagandperformshtmlencodingonthecontents.Inthiscase,
//weneedtopulltheoriginaltextcontentfromthetextnode's
//nodeValuepropertytoretrievetheunmangledcontent.
//NotethatIE6onlyunderstandstext/html
if(doc.body.firstChild&&doc.body.firstChild.nodeName.toUpperCase()=='PRE'){
response=doc.body.firstChild.firstChild.nodeValue;
}
if(response){
response=eval("("+response+")");
}else{
response={};
}
}
}else{
//responseisaxmldocument
response=doc;
}
settings.onComplete.call(self,file,response);
//Reloadblankpage,sothatreloadingmainpage
//doesnotre-submitthepost.Also,rememberto
//deletetheframe
toDeleteFlag=true;
//FixIEmixedcontentissue
iframe.src="javascript:'';";
});
},
/**
*Uploadfilecontainedinthis._input
*/
submit:function(){
varself=this,
settings=this._settings;
if(!this._input||this._input.value===''){
return;
}
varfile=fileFromPath(this._input.value);
//userreturnedfalsetocancelupload
if(false===settings.onSubmit.call(this,file,getExt(file))){
this._clearInput();
return;
}
//sendingrequest
variframe=this._createIframe();
varform=this._createForm(iframe);
//assumingfollowingstructure
//div->inputtype='file'
removeNode(this._input.parentNode);
removeClass(self._button,self._settings.hoverClass);
form.appendChild(this._input);
form.submit();
//requestset,cleanup
removeNode(form);
form=null;
removeNode(this._input);
this._input=null;
//GetresponsefromiframeandfireonCompleteeventwhenready
this._getResponse(iframe,file);
//getreadyfornextrequest
this._createInput();
}
};
})();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。