forked from LPology/Simple-Ajax-Uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleAjaxUploader.min.js
32 lines (32 loc) · 15.6 KB
/
SimpleAjaxUploader.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/** Simple Ajax Uploader v1.6.4 Copyright 2012-2013 LPology, LLC MIT license https://github.com/LPology/Simple-Ajax-Uploader */
(function(l,e,q){var c=l.ss||{};c.obj2string=function(a,b){var d=[];if("object"!==typeof a)return"";for(var f in a)if(a.hasOwnProperty(f)){var g=b?b+"["+f+"]":f,h=a[f];d.push("object"===typeof h?c.obj2string(h,g):encodeURIComponent(g)+"="+encodeURIComponent(h))}return d.join("&")};c.extendObj=function(a,b){if("object"!==typeof a||"object"!==typeof b)return!1;for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d])};c.contains=function(a,b){for(var d=a.length;d--;)if(a[d]===b)return!0;return!1};c.removeItem=
function(a,b){for(var d=a.length;d--;)a[d]==b&&a.splice(d,1)};c.addEvent=function(a,b,d){"string"===typeof a&&(a=e.getElementById(a));a.attachEvent?a.attachEvent("on"+b,d):a.addEventListener(b,d,!1)};c.removeEvent=function(a,b,d){"string"===typeof a&&(a=e.getElementById(a));a.attachEvent?a.detachEvent("on"+b,d):a.removeEventListener(b,d,!1)};c.newXHR=function(){if(typeof XMLHttpRequest!==q)return new l.XMLHttpRequest;if(l.ActiveXObject)try{return new l.ActiveXObject("Microsoft.XMLHTTP")}catch(a){return!1}};
c.parseJSON=function(a){if(!a||"string"!==typeof a)return!1;a=c.trim(a);if(l.JSON&&l.JSON.parse)try{return l.JSON.parse(a)}catch(b){return!1}return a&&/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,"@").replace(/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))?(new Function("return "+a))():!1};c.getOffsetSum=function(a){for(var b=0,d=0;a;)b+=parseInt(a.offsetTop,10),d+=parseInt(a.offsetLeft,10),a=a.offsetParent;return{top:b,
left:d}};c.getOffsetRect=function(a){a=a.getBoundingClientRect();var b=e.body,d=e.documentElement,c=a.left+(l.pageXOffset||d.scrollLeft||b.scrollLeft)-(d.clientLeft||b.clientLeft||0);return{top:Math.round(a.top+(l.pageYOffset||d.scrollTop||b.scrollTop)-(d.clientTop||b.clientTop||0)),left:Math.round(c)}};c.getOffset=function(a){return a.getBoundingClientRect?c.getOffsetRect(a):c.getOffsetSum(a)};c.getBox=function(a){var b,d;d=c.getOffset(a);b=d.left;d=d.top;return{left:b,right:b+a.offsetWidth,top:d,
bottom:d+a.offsetHeight}};c.addStyles=function(a,b){for(var d in b)b.hasOwnProperty(d)&&(a.style[d]=b[d])};c.copyLayout=function(a,b){var d=c.getBox(a);c.addStyles(b,{position:"absolute",left:d.left+"px",top:d.top+"px",width:a.offsetWidth+"px",height:a.offsetHeight+"px"})};c.toElement=function(){var a=e.createElement("div");return function(b){a.innerHTML=b;b=a.firstChild;a.removeChild(b);return b}}();c.getUID=function(){var a=0;return function(){return a++}}();c.trim=function(a){return a.toString().replace(/^\s+/,
"").replace(/\s+$/,"")};c.getFilename=function(a){return a.replace(/.*(\/|\\)/,"")};c.getExt=function(a){return-1!==a.indexOf(".")?a.replace(/.*[.]/,""):""};c.hasClass=function(a,b){return RegExp("(^| )"+b+"( |$)").test(a.className)};c.addClass=function(a,b){if(!b||""===b)return!1;c.hasClass(a,b)||(a.className+=" "+b)};c.removeClass=function(a,b){a.className=a.className.replace(RegExp("(^| )"+b+"( |$)")," ").replace(/^\s+|\s+$/g,"")};c.remove=function(a){a.parentNode&&a.parentNode.removeChild(a)};
c.verifyElem=function(a){"undefined"!==typeof jQuery&&a instanceof jQuery?a=a[0]:"string"===typeof a&&(/^#.*/.test(a)&&(a=a.slice(1)),a=e.getElementById(a));if(!a||1!==a.nodeType)return!1;"A"==a.nodeName.toUpperCase()&&c.addEvent(a,"click",function(a){a&&a.preventDefault?a.preventDefault():l.event&&(l.event.returnValue=!1)});return a};c.SimpleUpload=function(a){this._settings={button:"",url:"",progressUrl:!1,multiple:!1,maxUploads:3,queue:!0,checkProgressInterval:50,keyParamName:"APC_UPLOAD_PROGRESS",
allowedExtensions:[],accept:"",maxSize:!1,name:"",data:{},autoSubmit:!0,multipart:!1,method:"POST",responseType:"",debug:!1,hoverClass:"",focusClass:"",disabledClass:"",onChange:function(a,d){},onSubmit:function(a,d){},onProgress:function(a){},onUpdateFileSize:function(a){},onComplete:function(a,d){},onExtError:function(a,d){},onSizeError:function(a,d){},onError:function(a,d,c){},startXHR:function(a,c){},endXHR:function(a,c){},startNonXHR:function(a){},endNonXHR:function(a){}};c.extendObj(this._settings,
a);this._button=c.verifyElem(this._settings.button);if(!1===this._button)throw Error("Invalid button. Make sure the element you're passing exists.");!1===this._settings.multiple&&(this._settings.maxUploads=1);this._mouseOverButton=!1;this._file=this._size=this._ext=this._filename=this._input=null;this._queue=[];this._fileSizeBox=this._progressContainer=this._progressBar=null;this._activeUploads=0;this._doProgressUpdates=this._disabled=!1;this._activeProgressKeys=[];this._uploadProgressKey=null;this._maxUpdateFails=
10;this._isXhrUploadSupported()?(this._XhrIsSupported=!0,this.log("XHR upload supported")):(this._XhrIsSupported=!1,this.log("XHR upload not supported, using iFrame method"),this._settings.progressUrl&&this._getUploadProgressKey());this._createInput();this.enable();this.rerouteClicks(this._button)};c.SimpleUpload.prototype={log:function(a){this._settings.debug&&l.console&&console.log("[uploader] "+a)},setData:function(a){this._settings.data="object"===typeof a?a:{}},setProgressBar:function(a){this._progressBar=
c.verifyElem(a)},setFileSizeBox:function(a){this._fileSizeBox=c.verifyElem(a)},setProgressContainer:function(a){this._progressContainer=c.verifyElem(a)},getQueueSize:function(){return this._queue.length},removeCurrent:function(){0<this._queue.length&&this._queue.splice(0,1);this._cycleQueue()},disable:function(){var a=this._button.nodeName.toUpperCase();c.addClass(this._button,this._settings.disabledClass);this._disabled=!0;if("INPUT"==a||"BUTTON"==a)this._button.disabled=!0;this._input&&this._input.parentNode&&
(this._input.parentNode.style.visibility="hidden")},enable:function(){c.removeClass(this._button,this._settings.disabledClass);this._disabled=this._button.disabled=!1},_isXhrUploadSupported:function(){var a=e.createElement("input");a.type="file";return"multiple"in a&&"undefined"!=typeof File&&"undefined"!=typeof(new XMLHttpRequest).upload},_createInput:function(){var a=this,b=e.createElement("div");this._input=e.createElement("input");this._input.type="file";this._input.name=this._settings.name;this._XhrIsSupported&&
(this._input.multiple=!0,""!==this._settings.accept&&(this._input.accept=this._settings.accept));c.addStyles(b,{display:"block",position:"absolute",overflow:"hidden",margin:0,padding:0,opacity:0,direction:"ltr",zIndex:2147483583});c.addStyles(this._input,{position:"absolute",right:0,margin:0,padding:0,fontSize:"480px",fontFamily:"sans-serif",cursor:"pointer"});if("0"!==b.style.opacity){if("undefined"==typeof b.filters)throw Error("Opacity not supported by the browser");b.style.filter="alpha(opacity=0)"}c.addEvent(this._input,
"change",function(){var b,f;if(a._input&&""!==a._input.value){if(a._XhrIsSupported){b=c.getFilename(a._input.files[0].name);f=c.getExt(b);if(!1===a._settings.onChange.call(a,b,f))return;b=a._input.files.length;a._settings.multiple||(b=1);for(f=0;f<b;f++)a._queue.push(a._input.files[f])}else{b=c.getFilename(a._input.value);f=c.getExt(b);if(!1===a._settings.onChange.call(a,b,f))return;a._queue.push(a._input)}a._clearInput();a._settings.autoSubmit&&a.submit()}});c.addEvent(this._input,"mouseover",function(){!0===
a._mouseOverButton&&c.addClass(a._button,a._settings.hoverClass)});c.addEvent(this._input,"mouseout",function(){!0===a._mouseOverButton&&(c.removeClass(a._button,a._settings.hoverClass),c.removeClass(a._button,a._settings.focusClass),a._input.parentNode&&(a._input.parentNode.style.visibility="hidden"))});c.addEvent(this._input,"focus",function(){!0===a._mouseOverButton&&c.addClass(a._button,a._settings.focusClass)});c.addEvent(this._input,"blur",function(){!0===a._mouseOverButton&&c.removeClass(a._button,
a._settings.focusClass)});e.body.appendChild(b);b.appendChild(this._input)},_clearInput:function(){this._input&&(c.removeClass(this._button,this._settings.hoverClass),c.removeClass(this._button,this._settings.focusClass),c.remove(this._input.parentNode),this._input=null,this._createInput())},rerouteClicks:function(a){var b=this;a=c.verifyElem(a);c.addEvent(a,"mouseover",function(){b._disabled||(b._input||b._createInput(),b._mouseOverButton=a==b._button?!0:!1,c.copyLayout(a,b._input.parentNode),b._input.parentNode.style.visibility=
"visible")})},_createIframe:function(){var a=c.getUID(),b=c.toElement('<iframe src="javascript:false;" name="'+a+'" />');e.body.appendChild(b);b.style.display="none";b.id=a;return b},_createForm:function(a){var b=c.toElement('<form method="post" enctype="multipart/form-data"></form>');e.body.appendChild(b);b.style.display="none";b.action=this._settings.url;b.target=a.name;return b},_createHiddenInput:function(a,b){var c=e.createElement("input");c.type="hidden";c.name=a;c.value=b;return c},_errorFinish:function(a,
b,d,f,g,h,n){this._activeUploads--;this.log("error: "+b);this.log("server response :"+f);h&&(h.innerHTML="");n&&c.remove(n);this._settings.onError.call(this,d,a,f);this._cycleQueue()},_finish:function(a,b,d,f,g){var h=a;if("json"==this._settings.responseType.toLowerCase()&&(a=c.parseJSON(a),!1===a)){this._errorFinish("parseerror","Bad server response - unable to parse JSON",b,h,d,f,g);return}this._activeUploads--;this.log("server response: "+h);f&&(f.innerHTML="");g&&c.remove(g);this._settings.onComplete.call(this,
b,a);this._cycleQueue()},_cycleQueue:function(){this._progressContainer=this._progressBar=this._fileSizeBox=this._ext=this._filename=this._file=this._size=null;this._disabled&&this.enable();0<this._queue.length&&this._settings.autoSubmit&&this.submit()},_uploadXhr:function(){var a=this,b=this._settings,d=this._filename,f=this._size,g=this._fileSizeBox,h=this._progressBar,n=this._progressContainer,k=c.newXHR(),m={};!1===b.startXHR.call(this,d,f)?(this._disabled&&this.enable(),this._activeUploads--):
(g&&(g.innerHTML=f+"K"),m[b.name]=d,c.extendObj(m,b.data),m=b.url+"?"+c.obj2string(m),b.onProgress.call(this,0),h&&(h.style.width="0%"),c.addEvent(k.upload,"progress",function(c){c.lengthComputable&&(c=Math.round(100*(c.loaded/c.total)),b.onProgress.call(a,c),h&&(h.style.width=c+"%"))}),c.addEvent(k.upload,"error",function(){a._errorFinish("transfererror","Transfer error during upload",d,"None",h,g,n)}),k.onreadystatechange=function(){4===this.readyState&&(200===this.status||201===this.status?(b.endXHR.call(a,
d,f),a._finish(this.responseText,d,h,g,n)):a._errorFinish("servererror","Server error. Status: "+this.status,d,this.responseText,h,g,n))},k.open(b.method.toUpperCase(),m,!0),k.setRequestHeader("X-Requested-With","XMLHttpRequest"),k.setRequestHeader("X-File-Name",encodeURIComponent(d)),"json"==b.responseType.toLowerCase()&&k.setRequestHeader("Accept","application/json, text/javascript, */*; q=0.01"),!0===b.multipart?(m=new FormData,m.append(b.name,this._file),this.log("commencing upload using multipart form"),
k.send(m)):(k.setRequestHeader("Content-Type","application/octet-stream"),this.log("commencing upload using binary stream"),k.send(this._file)),this.removeCurrent())},_handleIframeResponse:function(a,b,d,f,g){var h;a.parentNode&&(h=a.contentWindow?a.contentWindow.document:a.contentDocument&&a.contentDocument.document?a.contentDocument.document:a.contentDocument,h.body&&!1===h.body.innerHTML||(h=h.body.innerHTML,c.remove(a),this._finish(h,b,d,f,g)))},_uploadIframe:function(){var a=this,b=this._settings,
d=b.checkProgressInterval,f=this._uploadProgressKey,g=this._progressBar,h=this._progressContainer,n=this._fileSizeBox,k=this._filename,m=this._createIframe(),e=this._createForm(m),p;this._doProgressUpdates&&(p=this._createHiddenInput(b.keyParamName,f),e.appendChild(p));if(!1===b.startNonXHR.call(this,k))this._disabled&&this.enable(),this._activeUploads--;else{p=b.data;for(var r in p)if(p.hasOwnProperty(r)){var q=this._createHiddenInput(r,p[r]);e.appendChild(q)}e.appendChild(this._file);b.onProgress.call(this,
0);g&&(g.style.width="0%");c.addEvent(m,"load",function(){c.contains(a._activeProgressKeys,f)&&c.removeItem(a._activeProgressKeys,f);c.removeEvent(m,"load",arguments.callee);b.endNonXHR.call(a,k);a._handleIframeResponse(m,k,g,n,h);f=null});a.log("commencing upload using iframe");e.submit();c.remove(e);e=null;a._doProgressUpdates&&(this._activeProgressKeys.push(f),l.setTimeout(function(){a.log("requesting first progress update");a._getUploadProgress(f,g,n,1)},d),this._alterProgressKey());this.removeCurrent()}},
_getUploadProgress:function(a,b,d,f){if(a){var g=this,h=this._settings,e=c.newXHR(),k=(new Date).getTime(),k=h.progressUrl+"?progresskey="+encodeURIComponent(a)+"&_="+k;e.onreadystatechange=function(){var e,k=h.checkProgressInterval;if(4===this.readyState)if(200===this.status){if((e=c.parseJSON(this.responseText))&&!0===e.success){f++;h.onUpdateFileSize.call(g,e.size);h.onProgress.call(g,e.pct);b&&(b.style.width=e.pct+"%");d&&e.size&&(d.innerHTML=e.size+"K");if(100>e.pct&&c.contains(g._activeProgressKeys,
a)){if(0===e.pct&&0===e.size&&f>=g._maxUpdateFails){g.log("reached limit of failed progress requests");return}l.setTimeout(function(){g._getUploadProgress(a,b,d,f);f=a=null},k)}k=null}}else a=null,g._doProgressUpdates=!1,g._uploadProgressKey=null,c.removeItem(g._activeProgressKeys,a),g.log("Progress error. Status: "+this.status+" Response: "+this.responseText);e=null};e.open("GET",k,!0);e.setRequestHeader("X-Requested-With","XMLHttpRequest");e.setRequestHeader("Accept","application/json, text/javascript, */*; q=0.01");
e.setRequestHeader("Cache-Control","no-cache");e.send();e=null}},_alterProgressKey:function(){this._uploadProgressKey+=c.getUID();57<this._uploadProgressKey.length&&(this._uploadProgressKey=c.getUID()+this._uploadProgressKey.substring(0,15))},_getUploadProgressKey:function(){var a=this,b=c.newXHR(),d=(new Date).getTime(),d=a._settings.progressUrl+"?getkey="+d;a._uploadProgressKey=null;b.onreadystatechange=function(){var b;4===this.readyState&&(200===this.status?(b=c.parseJSON(this.responseText))&&
b.key&&(a._uploadProgressKey=b.key,a.log("upload progress key received. Key: "+b.key)):a.log("Error retrieving progress key. Status: "+this.status+" Server response: "+this.responseText))};b.open("GET",d,!0);b.setRequestHeader("X-Requested-With","XMLHttpRequest");b.setRequestHeader("Accept","application/json, text/javascript, */*; q=0.01");b.setRequestHeader("Cache-Control","no-cache");b.send();b=null},_checkExtension:function(a){var b=this._settings.allowedExtensions,c=b.length;for(a=a.toLowerCase();c--;)if(b[c].toLowerCase()==
a)return!0;return!1},_checkFile:function(){var a=this._filename,b=this._ext,c=this._size;if(!this._file||""===a)return this.log("no file to upload"),!1;if(0<this._settings.allowedExtensions.length&&!this._checkExtension(b))return this.removeCurrent(),this.log("file extension not permitted"),this._settings.onExtError.call(this,a,b),!1;if(null!==c&&!1!==this._settings.maxSize&&c>this._settings.maxSize)return this.removeCurrent(),this.log(a+" exceeds "+this._settings.maxSize+"K limit"),this._settings.onSizeError.call(this,
a,c),!1;this.log("pre-upload file check successful");return!0},submit:function(){this._disabled||(this._activeUploads>=this._settings.maxUploads||1>this._queue.length)||(this._file=this._queue[0],this._XhrIsSupported?(this._filename=c.getFilename(this._file.name),this._size=Math.round(this._file.size/1024)):this._filename=c.getFilename(this._file.value),this._ext=c.getExt(this._filename),this._checkFile()&&!1!==this._settings.onSubmit.call(this,this._filename,this._ext)&&(this._activeUploads++,(!1===
this._settings.multiple||!1===this._settings.queue&&this._activeUploads>=this._settings.maxUploads)&&this.disable(),this._XhrIsSupported?this._uploadXhr():(!1!==this._settings.progressUrl&&null!==this._uploadProgressKey?this._doProgressUpdates=!0:(this._doProgressUpdates=!1,this.log("no upload progress - progressUrl not defined or progress key not available")),this._uploadIframe())))}};l.ss=c})(window,document);