From 953113ce64c253eb5d6460c29f82d21d4184b73c Mon Sep 17 00:00:00 2001 From: RubaXa Date: Fri, 8 Feb 2013 13:29:14 +0400 Subject: [PATCH] + v1.2.0: (#57) Chunked upload by wingedfox (Ilya Lebedev) --- FileAPI.min.js | 119 +++++++++++++++++++++++++------------------------ README.md | 119 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 159 insertions(+), 79 deletions(-) diff --git a/FileAPI.min.js b/FileAPI.min.js index 6482f2a5..83a3b047 100644 --- a/FileAPI.min.js +++ b/FileAPI.min.js @@ -4,61 +4,64 @@ * @author RubaXa * @build lib/canvas-to-blob lib/FileAPI.core lib/FileAPI.Image lib/FileAPI.Form lib/FileAPI.XHR lib/FileAPI.Flash */ -(function(a){var k=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,f;if(f=a.Blob)try{f=Boolean(new Blob)}catch(n){f=!1}var p=f;if(f=p)if(f=a.Uint8Array)try{f=100===(new Blob([new Uint8Array(100)])).size}catch(l){f=!1}var c=f,e=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder,r=(p||e)&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var g,f,q,l;g=0<=a.split(",")[0].indexOf("base64")?atob(a.split(",")[1]):decodeURIComponent(a.split(",")[1]);f=new ArrayBuffer(g.length);q=new Uint8Array(f); -for(l=0;l=a&&!c&&g.end()},isFail:function(){return c},fail:function(){!c&&b(c=!0)},end:function(){h||(h=!0,b())}};return g},each:f,afor:function(b,d){var a=0,c=b.length;g(b)&&c--?function C(){d(c!=a&&C,b[a],a++)}():d(!1)},extend:function(b){f(arguments,function(d){f(d,function(d,a){b[a]=d})});return b},isFile:function(b){return d&&b&&b instanceof v},isCanvas:function(b){return b&&N.test(b.nodeName)}, -getFilesFilter:function(b){return(b="string"==typeof b?b:b.getAttribute&&b.getAttribute("accept")||"")?RegExp("("+b.replace(/\./g,"\\.").replace(/,/g,"|")+")$","i"):/./},readAsDataURL:function(b,d){j.isCanvas(b)?c(b,d,"load",j.toDataURL(b)):e(b,d,"DataURL")},readAsBinaryString:function(b,d){u&&u.prototype.readAsBinaryString?e(b,d,"BinaryString"):e(b,function(b){if("load"==b.type)try{b.result=j.toBinaryString(b.result)}catch(a){b.type="error",b.message=a.toString()}d(b)},"DataURL")},readAsArrayBuffer:function(b, -d){e(b,d,"ArrayBuffer")},readAsText:function(b,d,a){a||(a=d,d="utf-8");e(b,a,"Text",d)},toDataURL:function(b){if("string"==typeof b)return b;if(b.toDataURL)return b.toDataURL("image/png")},toBinaryString:function(b){return a.atob(j.toDataURL(b).replace(P,""))},readAsImage:function(b,d,a){if(j.isFile(b))if(A){var h=A.createObjectURL(b);h===k?c(b,d,"error"):j.readAsImage(h,d,a)}else j.readAsDataURL(b,function(h){"load"==h.type?j.readAsImage(h.result,d,a):(a||"error"==h.type)&&c(b,d,h,null,{loaded:h.loaded, -total:h.total})});else j.isCanvas(b)?c(b,d,"load",b):F.test(b.nodeName)?b.complete?c(b,d,"load",b):l(b,"error abort load",function C(a){"load"==a.type&&A&&A.revokeObjectURL(b.src);p(b,"error abort load",C);c(b,d,a,b)}):b.iframe?c(b,d,{type:"error"}):(h=new Image,h.src=b.dataURL||b,j.readAsImage(h,d,a))},checkFileObj:function(b){var d={};"object"==typeof b?d=b:d.name=(b+"").split(/(\\|\/)/g).pop();d.type===k&&(d.type=d.name.split(".").pop());f(J,function(b,a){b.test(d.type)&&(d.type=a+"/"+d.type)}); -return d},getDropFiles:function(b,d){var a=[],c=(b.originalEvent||b||"").dataTransfer||{},h=g(c.items)&&c.items[0]&&r(c.items[0]),e=j.queue(function(){d(a)});f((h?c.items:c.files)||[],function(b){e.inc();if(h)w(b,function(b,d){!b&&a.push.apply(a,d);e.next()});else{var d=function(d){d&&a.push(b);e.next()};if(!b.type&&0==b.size%4096&&102400>=b.size)if(u)try{var c=new u;l(c,H,function(b){b="error"!=b.type;d(b);b&&c.abort()});c.readAsDataURL(b)}catch(s){d(!1)}else d(null);else d(!0)}});e.check()},getFiles:function(b, -a,c){var h=[];if(c)return j.filterFiles(j.getFiles(b),a,c),null;b.jquery&&(b.each(function(){h=h.concat(j.getFiles(this))}),b=h,h=[]);"string"==typeof a&&(a=j.getFilesFilter(a));b.originalEvent?b=x(b.originalEvent):b.srcElement&&(b=x(b));b.dataTransfer?b=b.dataTransfer:b.target&&(b=b.target);b.files?h=b.files:!d&&G.test(b&&b.tagName)?j.trim(b.value)&&(h=[j.checkFileObj(b.value)],h[0].blob=b,h[0].iframe=!0):g(b)&&(h=b);!a&&G.test(b&&b.tagName)&&(a=j.getFilesFilter(b));return j.filter(h,function(b){return!a|| -a.test(b.name)})},getInfo:function(b,d){var a={},c=K.concat();j.isFile(b)?function C(){var h=c.shift();h?h.test(b.type)?h(b,function(b,c){b?d(b):(j.extend(a,c),C())}):C():d(!1,a)}():d("not_support",a)},addInfoReader:function(b,d){d.test=function(d){return b.test(d)};K.push(d)},addMime:function(b,d){J[b]=RegExp("("+d.replace(/,/g,"|")+")$","i")},filter:function(b,d){for(var a=[],c=0,h=b.length,g;c>2,c=(c&3)<<4|h>>4;isNaN(h)?h=g=64:(h=(h& -15)<<2|g>>6,g=isNaN(g)?64:g&63);d+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(w)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(c)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(h)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(g)}return d}};f({image:"png,jpg,jpeg,bmp,gif,ico,tif,tiff,tga,pcx,cbz,cbr",audio:"m4a,flac,aac,rm,mpa,wav,wma,ogg,mp3,mp2,m3u,mod,amf,dmf,dsm,far,gdm,imf,it,m15,med,okt,s3m,stm,sfx,ult,uni,xm,sid,ac3,dts,cue,aif,aiff,wpl,ape,mac,mpc,mpp,shn,wv,nsf,spc,gym,adplug,adx,dsp,adp,ymf,ast,afc,hps,xsp", -video:"m4v,3gp,nsv,ts,ty,strm,rm,rmvb,m3u,ifo,mov,qt,divx,xvid,bivx,vob,nrg,img,iso,pva,wmv,asf,asx,ogm,m2v,avi,bin,dat,dvr-ms,mpg,mpeg,mp4,mkv,avc,vp3,svq3,nuv,viv,dv,fli,flv,wpl"},function(b,d){j.addMime(d,b)});j.addInfoReader(/^image/,function(b,d){if(!b.__dimensions){var a=b.__dimensions=j.defer();j.readAsImage(b,function(b){var d=b.target;a.resolve("load"==b.type?!1:"error",{width:d.width,height:d.height})})}b.__dimensions.then(d)});j.event.dnd=function(b,d,a){var c,h;a||(a=d,d=j.F);u?(n(b,"dragenter dragleave dragover", -function(b){for(var a=((b.originalEvent||b||"").dataTransfer||{}).types,g=a&&a.length;g--;)~a[g].indexOf("File")&&(b.preventDefault(),h!==b.type&&(h=b.type,"dragleave"!=h&&d.call(b.currentTarget,!0,b),clearTimeout(c),c=setTimeout(function(){d.call(b.currentTarget,"dragleave"!=h,b)},50)))}),n(b,"drop",function(b){b.preventDefault();h=0;d.call(b.currentTarget,!1,b);j.getDropFiles(b,function(d){a.call(b.currentTarget,d,b)})})):j.log("Drag'n'Drop -- not supported")};t&&!t.fn.dnd&&(t.fn.dnd=function(b, -d){return this.each(function(){j.event.dnd(this,b,d)})});a.FileAPI=j.extend(j,a.FileAPI);j.flashUrl||(j.flashUrl=j.staticPath+"FileAPI.flash.swf");j.flashImageUrl||(j.flashImageUrl=j.staticPath+"FileAPI.flash.image.swf")})(window); -(function(a,k,f){function n(a,c){if(!(this instanceof n))return new n(a);this.file=a;this.better=!c;this.matrix={sx:0,sy:0,sw:0,sh:0,dx:0,dy:0,dw:0,dh:0,resize:0,deg:0}}var p=Math.min,l=Math.round,c=!1,e={8:270,3:180,6:90};try{c=-1=k?(k=e,v=k/n):(v=c,k=v*n),k!=e||v!=c)g.sx=~~((e-k)/2),g.sy=~~((c-v)/2),e=k,c=v}else v&&("min"==v?(f=l(k=n?p(e,f):r*k),r=l(k>=n?f/k:p(c,r))));g.sw=e;g.sh=c;g.dw=f;g.dh=r;return g},_trans:function(a){this._load(this.file,function(c,e){c?a(c):this._apply(e,a)})},get:function(c){if(a.support.transform){var g=this;"auto"==g.matrix.deg?a.getInfo(this.file,function(a,f){g.matrix.deg= -e[f&&f.exif&&f.exif.Orientation]||0;g._trans(c)}):g._trans(c)}else c("not_support")},toData:function(a){this.get(a)}};n.transform=function(c,e,l,k){a.getInfo(c,function(r,p){var A={},v=a.queue(function(a){k(a,A)});r?v.fail():a.each(e,function(a,e){if(!v.isFail()){var g=n(p.nodeType?p:c);if("function"==typeof a)a(p,g);else if(a.width)g[a.preview?"preview":"resize"](a.width,a.height,a.type);else a.maxWidth&&(p.width>a.maxWidth||p.height>a.maxHeight)&&g.resize(a.maxWidth,a.maxHeight,"max");a.rotate=== -f&&l&&(a.rotate="auto");g.rotate(a.rotate);v.inc();g.toData(function(d,a){d?v.fail():(A[e]=a,v.next())})}})})};a.support.canvas=a.support.transform=c;a.Image=n})(FileAPI,document); -(function(a,k,f){var n=k.encodeURIComponent,p=k.FormData;k=function(){this.items=[]};k.prototype={append:function(a,c,e,f){this.items.push({name:a,blob:c&&c.blob||c,file:e||c.name,type:f||c.type})},each:function(a){for(var c=0,e=this.items.length;c',c.xhr.abort=function(){var a=e.getElementsByName("iframe")[0];if(a)try{a.stop?a.stop():a.contentWindow.stop?a.contentWindow.stop():a.contentWindow.document.execCommand("Stop")}catch(c){}e=null},n=e.getElementsByTagName("form")[0],n.appendChild(l), -k.log(n.parentNode.innerHTML),document.body.appendChild(e),c.xhr.node=e,a[r]=function(a,f,k){c.readyState=4;c.responseText=k;c.end(a,f);e=null},c.readyState=2,n.submit(),n=null):(e=c.xhr=k.getXHR(),e.open("POST",n,!0),e.withCredential="true",(!f.headers||!f.headers["X-Requested-With"])&&e.setRequestHeader("X-Requested-With","XMLHttpRequest"),k.each(f.headers,function(a,c){e.setRequestHeader(c,a)}),e.upload&&e.upload.addEventListener("progress",k.throttle(function(a){f.progress(a,c,f)},100),!1),e.onreadystatechange= -function(){c.status=e.status;c.statusText=e.statusText;c.readyState=e.readyState;if(4==e.readyState){for(var a in{"":1,XML:1,Text:1,Body:1})c["response"+a]=e["response"+a];e.onreadystatechange=null;c.end(e.status);e=null}},k.isArray(l)?(e.setRequestHeader("Content-Type","multipart/form-data; boundary=_"+k.expando),l=l.join("")+"--_"+k.expando+"--",e.sendAsBinary?e.sendAsBinary(l):(r=Array.prototype.map.call(l,function(a){return a.charCodeAt(0)&255}),e.send((new Uint8Array(r)).buffer))):e.send(l))}}; -k.XHR=n})(window,FileAPI); -(function(a,k,f){var n=a.support,p=k.navigator,l=p.mimeTypes,c=!1;if(p.plugins&&"object"==typeof p.plugins["Shockwave Flash"])c=p.plugins["Shockwave Flash"].description&&!(l&&l["application/x-shockwave-flash"]&&!l["application/x-shockwave-flash"].enabledPlugin);else try{c=!(!k.ActiveXObject||!new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))}catch(e){}n.flash=c;if(a.support.flash&&(!a.support.html5||a.cors&&!a.support.cors)){var r=function(a){return('').replace(/#(\w+)#/ig,function(c,e){return a[e]})},w=function(a,c){if(a&&a.style){var e,f;for(e in c){f=c[e];"number"==typeof f&&(f+="px");try{a.style[e]=f}catch(g){}}}},g=function(d,c){a.each(c,function(a,c){var h=d[c];d[c]=function(){this.parent=h;return a.apply(this,arguments)}})},x=function(d){var c=d.wid=a.uid();m._fn[c]=d;return"FileAPI.Flash._fn."+c},q=function(a){try{m._fn[a.wid]=null,delete m._fn[a.wid]}catch(c){}}, -D=function(a,c){if(!u.test(a)){if(/^\.\//.test(a)||"/"!=a.charAt(0)){var e=location.pathname,e=e.substr(0,e.lastIndexOf("/"));a=(e+"/"+a).replace("/./","/")}"//"!=a.substr(0,2)&&(a="//"+location.host+a);u.test(a)||(a=location.protocol+a)}c&&(a+=(/\?/.test(a)?"&":"?")+c);return a},y=a.uid(),A=0,v={},u=/^https?:/i,m={_fn:{},init:function(){var d=f.body&&f.body.firstChild;if(d){do if(1==d.nodeType){a.log("FlashAPI.Flash.init...");var c=f.createElement("div");w(c,{top:1,right:1,width:5,height:5,position:"absolute"}); -d.parentNode.insertBefore(c,d);m.publish(c,y);return}while(d=d.nextSibling)}10>A&&setTimeout(m.init,50*++A)},publish:function(d,c){d.innerHTML=r({id:c,src:D(a.flashUrl,"r="+a.version),wmode:"transparent",flashvars:"callback=FileAPI.Flash.event&flashId="+c+"&storeKey="+navigator.userAgent.match(/\d/ig).join("")+"_"+a.version+(m.isReady||(a.pingUrl?"&ping="+a.pingUrl:""))})},ready:function(){m.ready=a.F;m.isReady=!0;m.patch();a.event.on(f,"mouseover",m.mouseover);a.event.on(f,"click",function(a){m.mouseover(a)&& -(a.preventDefault?a.preventDefault():a.returnValue=!0)})},getWrapper:function(a){do if(/js-fileapi-wrapper/.test(a.className))return a;while((a=a.parentNode)&&a!==f.body)},mouseover:function(d){d=a.event.fix(d).target;if(/input/i.test(d.nodeName)&&"file"==d.type){var c=d.getAttribute(y);if("i"==c||"r"==c)return!1;if("p"!=c){d.setAttribute(y,"i");var c=f.createElement("div"),e=m.getWrapper(d);if(!e){a.log("flash.mouseover.error: js-fileapi-wrapper not found");return}w(c,{top:0,left:0,width:d.offsetWidth+ -100,height:d.offsetHeight+100,zIndex:"1000000",position:"absolute"});e.appendChild(c);m.publish(c,a.uid());d.setAttribute(y,"p")}return!0}},event:function(d){var c=d.type;if("ready"==c){try{m.getInput(d.flashId).setAttribute(y,"r")}catch(e){}m.ready();setTimeout(function(){m.mouseenter(d)},50);return!0}"ping"===c?a.log("(flash -> js).ping:",[d.status,d.savedStatus],d.error):"log"===c?a.log("(flash -> js).log:",d.target):c in m&&setTimeout(function(){a.log("Flash.event."+d.type+":",d);m[c](d)},1)}, -mouseenter:function(a){var c=m.getInput(a.flashId);c&&(m.cmd(a,"multiple",null!==c.getAttribute("multiple")),m.cmd(a,"accept",(c.getAttribute("accept")||"*").replace(/\./g,"")))},get:function(a){return f[a]||k[a]||f.embeds[a]},getInput:function(a){try{var c=m.getWrapper(m.get(a));if(c)return c.getElementsByTagName("input")[0]}catch(e){}},select:function(d){var c=m.getInput(d.flashId),e=a.uid(c);d=d.target.files;a.each(d,function(d){a.checkFileObj(d)});v[e]=d;f.createEvent?(e=f.createEvent("Event"), -e.initEvent("change",!0,!1),c.dispatchEvent(e)):f.createEventObject&&(e=f.createEventObject(),c.fireEvent("onchange",e))},cmd:function(d,c,e,f){try{return a.log("(js -> flash)."+c+":",e),m.get(d.flashId||d).cmd(c,e)}catch(g){a.log("(js -> flash).onError:",g),f||setTimeout(function(){m.cmd(d,c,e,!0)},50)}},patch:function(){a.flashEngine=a.support.transform=!0;g(a,{getFiles:function(d,c,e){if(e)return a.filterFiles(a.getFiles(d),c,e),null;var f=a.isArray(d)?d:v[a.uid(d.target||d.srcElement||d)];if(!f)return this.parent.apply(this, -arguments);c&&(c=a.getFilesFilter(c),f=a.filter(f,function(a){return c.test(a.name)}));return f},getInfo:function(a,c){if(a&&!a.flashId)this.parent.apply(this,arguments);else{if(!a.__info){var e=a.__info=FileAPI.defer();m.cmd(a,"getFileInfo",{id:a.id,callback:x(function F(c,f){q(F);e.resolve(c,a.info=f)})})}a.__info.then(c)}}});a.support.transform=!0;g(FileAPI.Image.prototype,{get:function(a,c){this.set({scaleMode:c||"noScale"});this.parent(a)},_load:function(d,c){a.log("FileAPI.Image._load:",d); -if(d&&!d.flashId)this.parent.apply(this,arguments);else{var e=this;a.getInfo(d,function(a){c.call(e,a,d)})}},_apply:function(d,c){a.log("FileAPI.Image._apply:",d);if(d&&!d.flashId)this.parent.apply(this,arguments);else{var e=this.getMatrix(d.info);m.cmd(d,"imageTransform",{id:d.id,matrix:e,callback:x(function F(g,k){a.log("FileAPI.Image._apply.callback:",g);q(F);if(g)c(g);else if(!a.support.dataURI||3E4=a&&!c&&n.end()},isFail:function(){return c},fail:function(){!c&&b(c=!0)},end:function(){g||(g=!0,b())}};return n},each:h,afor:function(b,d){var a=0,c=b.length; +g(b)&&c--?function B(){d(c!=a&&B,b[a],a++)}():d(!1)},extend:function(b){h(arguments,function(d){h(d,function(d,a){b[a]=d})});return b},isFile:function(b){return d&&b&&b instanceof s},isCanvas:function(b){return b&&U.test(b.nodeName)},getFilesFilter:function(b){return(b="string"==typeof b?b:b.getAttribute&&b.getAttribute("accept")||"")?RegExp("("+b.replace(/\./g,"\\.").replace(/,/g,"|")+")$","i"):/./},readAsDataURL:function(b,d){j.isCanvas(b)?c(b,d,"load",j.toDataURL(b)):e(b,d,"DataURL")},readAsBinaryString:function(b, +d){u&&u.prototype.readAsBinaryString?e(b,d,"BinaryString"):e(b,function(b){if("load"==b.type)try{b.result=j.toBinaryString(b.result)}catch(a){b.type="error",b.message=a.toString()}d(b)},"DataURL")},readAsArrayBuffer:function(b,d){e(b,d,"ArrayBuffer")},readAsText:function(b,d,a){a||(a=d,d="utf-8");e(b,a,"Text",d)},toDataURL:function(b){if("string"==typeof b)return b;if(b.toDataURL)return b.toDataURL("image/png")},toBinaryString:function(b){return a.atob(j.toDataURL(b).replace(W,""))},readAsImage:function(b, +d,a){if(j.isFile(b))if(D){var g=D.createObjectURL(b);g===k?c(b,d,"error"):j.readAsImage(g,d,a)}else j.readAsDataURL(b,function(g){"load"==g.type?j.readAsImage(g.result,d,a):(a||"error"==g.type)&&c(b,d,g,null,{loaded:g.loaded,total:g.total})});else j.isCanvas(b)?c(b,d,"load",b):G.test(b.nodeName)?b.complete?c(b,d,"load",b):f(b,"error abort load",function B(a){"load"==a.type&&D&&D.revokeObjectURL(b.src);l(b,"error abort load",B);c(b,d,a,b)}):b.iframe?c(b,d,{type:"error"}):(g=new Image,g.src=b.dataURL|| +b,j.readAsImage(g,d,a))},checkFileObj:function(b){var d={};"object"==typeof b?d=b:d.name=(b+"").split(/(\\|\/)/g).pop();d.type===k&&(d.type=d.name.split(".").pop());h(P,function(b,a){b.test(d.type)&&(d.type=a+"/"+d.type)});return d},getDropFiles:function(b,d){var a=[],c=(b.originalEvent||b||"").dataTransfer||{},n=g(c.items)&&c.items[0]&&m(c.items[0]),e=j.queue(function(){d(a)});h((n?c.items:c.files)||[],function(b){e.inc();if(n)q(b,function(b,d){!b&&a.push.apply(a,d);e.next()});else{var d=function(d){d&& +a.push(b);e.next()};if(!b.type&&0==b.size%4096&&102400>=b.size)if(u)try{var c=new u;f(c,L,function(b){b="error"!=b.type;d(b);b&&c.abort()});c.readAsDataURL(b)}catch(g){d(!1)}else d(null);else d(!0)}});e.check()},getFiles:function(b,a,c){var n=[];if(c)return j.filterFiles(j.getFiles(b),a,c),null;b.jquery&&(b.each(function(){n=n.concat(j.getFiles(this))}),b=n,n=[]);"string"==typeof a&&(a=j.getFilesFilter(a));b.originalEvent?b=A(b.originalEvent):b.srcElement&&(b=A(b));b.dataTransfer?b=b.dataTransfer: +b.target&&(b=b.target);b.files?n=b.files:!d&&I.test(b&&b.tagName)?j.trim(b.value)&&(n=[j.checkFileObj(b.value)],n[0].blob=b,n[0].iframe=!0):g(b)&&(n=b);!a&&I.test(b&&b.tagName)&&(a=j.getFilesFilter(b));return j.filter(n,function(b){return!a||a.test(b.name)})},getInfo:function(b,d){var a={},c=R.concat();j.isFile(b)?function B(){var g=c.shift();g?g.test(b.type)?g(b,function(b,c){b?d(b):(j.extend(a,c),B())}):B():d(!1,a)}():d("not_support",a)},addInfoReader:function(b,d){d.test=function(d){return b.test(d)}; +R.push(d)},addMime:function(b,d){P[b]=RegExp("("+d.replace(/,/g,"|")+")$","i")},filter:function(b,d){for(var a=[],c=0,g=b.length,n;c>2,c=(c&3)<<4|g>>4;isNaN(g)?g=n=64:(g=(g&15)<<2|n>>6,n=isNaN(n)?64:n&63);d+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(e)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(c)+ +"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(g)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(n)}return d}};h({image:"png,jpg,jpeg,bmp,gif,ico,tif,tiff,tga,pcx,cbz,cbr",audio:"m4a,flac,aac,rm,mpa,wav,wma,ogg,mp3,mp2,m3u,mod,amf,dmf,dsm,far,gdm,imf,it,m15,med,okt,s3m,stm,sfx,ult,uni,xm,sid,ac3,dts,cue,aif,aiff,wpl,ape,mac,mpc,mpp,shn,wv,nsf,spc,gym,adplug,adx,dsp,adp,ymf,ast,afc,hps,xsp",video:"m4v,3gp,nsv,ts,ty,strm,rm,rmvb,m3u,ifo,mov,qt,divx,xvid,bivx,vob,nrg,img,iso,pva,wmv,asf,asx,ogm,m2v,avi,bin,dat,dvr-ms,mpg,mpeg,mp4,mkv,avc,vp3,svq3,nuv,viv,dv,fli,flv,wpl"}, +function(b,d){j.addMime(d,b)});j.addInfoReader(/^image/,function(b,d){if(!b.__dimensions){var a=b.__dimensions=j.defer();j.readAsImage(b,function(b){var d=b.target;a.resolve("load"==b.type?!1:"error",{width:d.width,height:d.height})})}b.__dimensions.then(d)});j.event.dnd=function(b,d,a){var c,g;a||(a=d,d=j.F);u?(r(b,"dragenter dragleave dragover",function(b){for(var a=((b.originalEvent||b||"").dataTransfer||{}).types,n=a&&a.length;n--;)~a[n].indexOf("File")&&(b.preventDefault(),g!==b.type&&(g=b.type, +"dragleave"!=g&&d.call(b.currentTarget,!0,b),clearTimeout(c),c=setTimeout(function(){d.call(b.currentTarget,"dragleave"!=g,b)},50)))}),r(b,"drop",function(b){b.preventDefault();g=0;d.call(b.currentTarget,!1,b);j.getDropFiles(b,function(d){a.call(b.currentTarget,d,b)})})):j.log("Drag'n'Drop -- not supported")};t&&!t.fn.dnd&&(t.fn.dnd=function(b,d){return this.each(function(){j.event.dnd(this,b,d)})});a.FileAPI=j.extend(j,a.FileAPI);j.flashUrl||(j.flashUrl=j.staticPath+"FileAPI.flash.swf");j.flashImageUrl|| +(j.flashImageUrl=j.staticPath+"FileAPI.flash.image.swf")})(window); +(function(a,k,h){function r(a,c){if(!(this instanceof r))return new r(a);this.file=a;this.better=!c;this.matrix={sx:0,sy:0,sw:0,sh:0,dx:0,dy:0,dw:0,dh:0,resize:0,deg:0}}var l=Math.min,f=Math.round,c=!1,e={8:270,3:180,6:90};try{c=-1=m?(m=e,s=m/r):(s=c,m=s*r),m!=e||s!=c)g.sx=~~((e-m)/2),g.sy=~~((c-s)/2),e=m,c=s}else s&&("min"==s?(h=f(m=r?l(e,h):k*m),k=f(m>=r?h/m:l(c,k))));g.sw=e;g.sh=c;g.dw=h;g.dh=k;return g},_trans:function(a){this._load(this.file,function(c,e){c?a(c):this._apply(e,a)})},get:function(c){if(a.support.transform){var g=this;"auto"==g.matrix.deg?a.getInfo(this.file,function(a,f){g.matrix.deg= +e[f&&f.exif&&f.exif.Orientation]||0;g._trans(c)}):g._trans(c)}else c("not_support")},toData:function(a){this.get(a)}};r.transform=function(c,g,e,f){a.getInfo(c,function(l,m){var k={},s=a.queue(function(a){f(a,k)});l?s.fail():a.each(g,function(a,g){if(!s.isFail()){var f=r(m.nodeType?m:c);if("function"==typeof a)a(m,f);else if(a.width)f[a.preview?"preview":"resize"](a.width,a.height,a.type);else a.maxWidth&&(m.width>a.maxWidth||m.height>a.maxHeight)&&f.resize(a.maxWidth,a.maxHeight,"max");a.rotate=== +h&&e&&(a.rotate="auto");f.rotate(a.rotate);s.inc();f.toData(function(a,c){a?s.fail():(k[g]=c,s.next())})}})})};a.support.canvas=a.support.transform=c;a.Image=r})(FileAPI,document); +(function(a,k,h){var r=k.encodeURIComponent,l=k.FormData;k=function(){this.items=[]};k.prototype={append:function(a,c,e,h){this.items.push({name:a,blob:c&&c.blob||c,file:e||c.name,type:h||c.type})},each:function(a){for(var c=0,e=this.items.length;c',c.xhr.abort=function(){var a=e.getElementsByName("iframe")[0];if(a)try{a.stop?a.stop():a.contentWindow.stop?a.contentWindow.stop():a.contentWindow.document.execCommand("Stop")}catch(c){}e=null},q=e.getElementsByTagName("form")[0],q.appendChild(f), +k.log(q.parentNode.innerHTML),document.body.appendChild(e),c.xhr.node=e,a[m]=function(a,f,h){c.readyState=4;c.responseText=h;c.end(a,f);e=null},c.readyState=2,q.submit(),q=null):(e=c.xhr=k.getXHR(),e.open("POST",q,!0),e.withCredential="true",(!h.headers||!h.headers["X-Requested-With"])&&e.setRequestHeader("X-Requested-With","XMLHttpRequest"),k.each(h.headers,function(a,c){e.setRequestHeader(c,a)}),k.support.chunked&&0').replace(/#(\w+)#/ig,function(c,e){return a[e]})},q=function(a,c){if(a&&a.style){var e,f;for(e in c){f=c[e];"number"==typeof f&&(f+="px");try{a.style[e]=f}catch(g){}}}},g=function(d,c){a.each(c,function(a,c){var e=d[c];d[c]=function(){this.parent=e;return a.apply(this,arguments)}})},A=function(d){var c=d.wid=a.uid();p._fn[c]=d;return"FileAPI.Flash._fn."+c},v=function(a){try{p._fn[a.wid]= +null,delete p._fn[a.wid]}catch(c){}},F=function(a,c){if(!u.test(a)){if(/^\.\//.test(a)||"/"!=a.charAt(0)){var e=location.pathname,e=e.substr(0,e.lastIndexOf("/"));a=(e+"/"+a).replace("/./","/")}"//"!=a.substr(0,2)&&(a="//"+location.host+a);u.test(a)||(a=location.protocol+a)}c&&(a+=(/\?/.test(a)?"&":"?")+c);return a},w=a.uid(),D=0,s={},u=/^https?:/i,p={_fn:{},init:function(){var d=h.body&&h.body.firstChild;if(d){do if(1==d.nodeType){a.log("FlashAPI.Flash.init...");var c=h.createElement("div");q(c, +{top:1,right:1,width:5,height:5,position:"absolute"});d.parentNode.insertBefore(c,d);p.publish(c,w);return}while(d=d.nextSibling)}10>D&&setTimeout(p.init,50*++D)},publish:function(d,c){d.innerHTML=m({id:c,src:F(a.flashUrl,"r="+a.version),wmode:"transparent",flashvars:"callback=FileAPI.Flash.event&flashId="+c+"&storeKey="+navigator.userAgent.match(/\d/ig).join("")+"_"+a.version+(p.isReady||(a.pingUrl?"&ping="+a.pingUrl:""))})},ready:function(){p.ready=a.F;p.isReady=!0;p.patch();a.event.on(h,"mouseover", +p.mouseover);a.event.on(h,"click",function(a){p.mouseover(a)&&(a.preventDefault?a.preventDefault():a.returnValue=!0)})},getWrapper:function(a){do if(/js-fileapi-wrapper/.test(a.className))return a;while((a=a.parentNode)&&a!==h.body)},mouseover:function(d){d=a.event.fix(d).target;if(/input/i.test(d.nodeName)&&"file"==d.type){var c=d.getAttribute(w);if("i"==c||"r"==c)return!1;if("p"!=c){d.setAttribute(w,"i");var c=h.createElement("div"),e=p.getWrapper(d);if(!e){a.log("flash.mouseover.error: js-fileapi-wrapper not found"); +return}q(c,{top:0,left:0,width:d.offsetWidth+100,height:d.offsetHeight+100,zIndex:"1000000",position:"absolute"});e.appendChild(c);p.publish(c,a.uid());d.setAttribute(w,"p")}return!0}},event:function(d){var c=d.type;if("ready"==c){try{p.getInput(d.flashId).setAttribute(w,"r")}catch(e){}p.ready();setTimeout(function(){p.mouseenter(d)},50);return!0}"ping"===c?a.log("(flash -> js).ping:",[d.status,d.savedStatus],d.error):"log"===c?a.log("(flash -> js).log:",d.target):c in p&&setTimeout(function(){a.log("Flash.event."+ +d.type+":",d);p[c](d)},1)},mouseenter:function(a){var c=p.getInput(a.flashId);c&&(p.cmd(a,"multiple",null!==c.getAttribute("multiple")),p.cmd(a,"accept",(c.getAttribute("accept")||"*").replace(/\./g,"")))},get:function(a){return h[a]||k[a]||h.embeds[a]},getInput:function(a){try{var c=p.getWrapper(p.get(a));if(c)return c.getElementsByTagName("input")[0]}catch(e){}},select:function(d){var c=p.getInput(d.flashId),e=a.uid(c);d=d.target.files;a.each(d,function(d){a.checkFileObj(d)});s[e]=d;h.createEvent? +(e=h.createEvent("Event"),e.initEvent("change",!0,!1),c.dispatchEvent(e)):h.createEventObject&&(e=h.createEventObject(),c.fireEvent("onchange",e))},cmd:function(d,c,e,f){try{return a.log("(js -> flash)."+c+":",e),p.get(d.flashId||d).cmd(c,e)}catch(g){a.log("(js -> flash).onError:",g),f||setTimeout(function(){p.cmd(d,c,e,!0)},50)}},patch:function(){a.flashEngine=a.support.transform=!0;g(a,{getFiles:function(d,c,e){if(e)return a.filterFiles(a.getFiles(d),c,e),null;var f=a.isArray(d)?d:s[a.uid(d.target|| +d.srcElement||d)];if(!f)return this.parent.apply(this,arguments);c&&(c=a.getFilesFilter(c),f=a.filter(f,function(a){return c.test(a.name)}));return f},getInfo:function(a,c){if(a&&!a.flashId)this.parent.apply(this,arguments);else{if(!a.__info){var e=a.__info=FileAPI.defer();p.cmd(a,"getFileInfo",{id:a.id,callback:A(function G(c,f){v(G);e.resolve(c,a.info=f)})})}a.__info.then(c)}}});a.support.transform=!0;g(FileAPI.Image.prototype,{get:function(a,c){this.set({scaleMode:c||"noScale"});this.parent(a)}, +_load:function(c,e){a.log("FileAPI.Image._load:",c);if(c&&!c.flashId)this.parent.apply(this,arguments);else{var f=this;a.getInfo(c,function(a){e.call(f,a,c)})}},_apply:function(c,e){a.log("FileAPI.Image._apply:",c);if(c&&!c.flashId)this.parent.apply(this,arguments);else{var f=this.getMatrix(c.info);p.cmd(c,"imageTransform",{id:c.id,matrix:f,callback:A(function G(g,k){a.log("FileAPI.Image._apply.callback:",g);v(G);if(g)e(g);else if(!a.support.dataURI||3E4 @@ -11,8 +11,9 @@ ## Support * Multiupload: all browsers that support HTML5 or [Flash](#flash-settings) * Drag'n'Drop upload: files (HTML5) & directories (Chrome 21+) + * [Chunked](#chunked) file upload (HTML5) * Upload one file: all browsers - * Working with Images: IE6+, FF 3.6+, Chrome 10+, Opera 11.1+, Safari 5.4+ + * Working with [Images](#images): IE6+, FF 3.6+, Chrome 10+, Opera 11.1+, Safari 5.4+ + crop, resize, preview & rotate (HTML5 or Flash) + auto orientation by exif (HTML5, if include FileAPI.exif.js or Flash) @@ -84,7 +85,7 @@ FileAPI.event.on(input, 'change', function (evt){ var xhr = FileAPI.upload({ url: '...', data: { foo: 'bar' }, // POST-data (iframe, flash, html5) - headers: { 'x-header': '...' }, // request headers (flash, html5) + headers: { 'x-header': '...' }, // request headers (html5) files: { files: FileAPI.filter(fileList, function (file){ return !/image/.test(file.type); }), pictures: imageList @@ -138,6 +139,7 @@ FileAPI.event.on(input, 'change', function (evt){ * jQuery('#el').dnd(onHover, onDrop) + ### FileAPI.Image * .crop(width[, height]) * .crop(x, y, width[, height]) @@ -160,6 +162,7 @@ FileAPI.event.on(input, 'change', function (evt){ * FileAPI.support.`flash:Boolean` * FileAPI.support.`canvas:Boolean` * FileAPI.support.`dataURI:Boolean` +* FileAPI.support.`chunked:Boolean` * FileAPI.each(`obj:Object|Array`, `fn:function`, `context:Mixed`) * FileAPI.extend(`dst:Object`, `src:Object`)`:Object` * FileAPI.filter(`list:Array`, `iterator:Function`)`:Array` @@ -167,22 +170,6 @@ FileAPI.event.on(input, 'change', function (evt){ * FileAPI.toBinaryString(`str:Base64`)`:String` - -### Flash settings -```html - - -``` - --------------------------------------- @@ -220,7 +207,7 @@ function onDrop(evt){ var el = document.getElementById('el'); FileAPI.event.dnd(el, function (over/**Boolean*/, evt/**Event*/){ - el.style.background = ever ? 'red' : ''; + el.style.background = over ? 'red' : ''; }, function (files/**Array*/, evt/**Event*/){ // ... }); @@ -315,6 +302,10 @@ var xhr = FileAPI.upload({ images: FileAPI.filter(files, function (file){ return /image/.test(file.type); }), customFile: { file: 'generate.txt', blob: customFileBlob } }, + + chunkSize: 0, // or chunk size in bytes, eg: FileAPI.MB*.5 (html5) + chunkUploadRetry: 0, // number of retries during upload chunks (html5) + imageTransform: { maxWidth: 1024, maxHeight: 768 @@ -419,7 +410,87 @@ FileAPI.upload({ ``` ----- +----- + + + +### Flash settings +```html + + +``` + +#### Flash-request ([FileReference](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html)) +The following sample HTTP POST request is sent from Flash Player to a server-side script if no parameters are specified: +``` + POST /handler.cfm HTTP/1.1 + Accept: text/* + Content-Type: multipart/form-data; + boundary=----------Ij5ae0ae0KM7GI3KM7 + User-Agent: Shockwave Flash + Host: www.example.com + Content-Length: 421 + Connection: Keep-Alive + Cache-Control: no-cache + + ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7 + Content-Disposition: form-data; name="Filename" + + MyFile.jpg + ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7 + Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg" + Content-Type: application/octet-stream + + FileDataHere + ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7 + Content-Disposition: form-data; name="Upload" + + Submit Query + ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7-- +``` + + + +----- + + + + +### Chunked file upload (html5) +```js +FileAPI.upload({ + url: '...' + , files: fileList + , chunkSize: .5 * FileAPI.MB // 512KB + , chunkUploadRetry: 1 + , complete: function (err, xhr){} +}); +``` + +All relations between client and server is operated on level of HTTP's titles. Client sets up titles for transferring separate chunk. +* [Content-Range](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16): bytes \-\/\ +* [Content-Disposition](http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1): attachment; filename=\ + +Other titles are not used. Tracking name's uniqueness of delegating file is not executed. It is left on developer's consideration. + +In response to delegating chunk server can reply following codes: +* 200, 201 — chunk is successfully saved +* 416, 500 — repairable error, you can continue upload. + +All the other codes — fatal error, user's involvement is recommend. + + + +----- @@ -489,6 +560,8 @@ FileAPI.upload({ ``` + + --- @@ -595,6 +668,10 @@ FileAPI.upload({ ## Changelog +### 1.2.0 + * [#57](https://github.com/mailru/FileAPI/issues/57): Chunked file upload + + ### 1.1.0 * [#54](https://github.com/mailru/FileAPI/issues/54): added `FileAPI.flashUrl` and `FileAPI.flashImageUrl`