webuploader.html5only.js 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561
  1. /*! WebUploader 0.1.2 */
  2. /**
  3. * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。
  4. *
  5. * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。
  6. */
  7. (function (root, factory) {
  8. var modules = {},
  9. // 内部require, 简单不完全实现。
  10. // https://github.com/amdjs/amdjs-api/wiki/require
  11. _require = function (deps, callback) {
  12. var args, len, i;
  13. // 如果deps不是数组,则直接返回指定module
  14. if (typeof deps === 'string') {
  15. return getModule(deps);
  16. } else {
  17. args = [];
  18. for (len = deps.length, i = 0; i < len; i++) {
  19. args.push(getModule(deps[i]));
  20. }
  21. return callback.apply(null, args);
  22. }
  23. },
  24. // 内部define,暂时不支持不指定id.
  25. _define = function (id, deps, factory) {
  26. if (arguments.length === 2) {
  27. factory = deps;
  28. deps = null;
  29. }
  30. _require(deps || [], function () {
  31. setModule(id, factory, arguments);
  32. });
  33. },
  34. // 设置module, 兼容CommonJs写法。
  35. setModule = function (id, factory, args) {
  36. var module = {
  37. exports: factory
  38. },
  39. returned;
  40. if (typeof factory === 'function') {
  41. args.length || (args = [_require, module.exports, module]);
  42. returned = factory.apply(null, args);
  43. returned !== undefined && (module.exports = returned);
  44. }
  45. modules[id] = module.exports;
  46. },
  47. // 根据id获取module
  48. getModule = function (id) {
  49. var module = modules[id] || root[id];
  50. if (!module) {
  51. throw new Error('`' + id + '` is undefined');
  52. }
  53. return module;
  54. },
  55. // 将所有modules,将路径ids装换成对象。
  56. exportsTo = function (obj) {
  57. var key, host, parts, part, last, ucFirst;
  58. // make the first character upper case.
  59. ucFirst = function (str) {
  60. return str && (str.charAt(0).toUpperCase() + str.substr(1));
  61. };
  62. for (key in modules) {
  63. host = obj;
  64. if (!modules.hasOwnProperty(key)) {
  65. continue;
  66. }
  67. parts = key.split('/');
  68. last = ucFirst(parts.pop());
  69. while ((part = ucFirst(parts.shift()))) {
  70. host[part] = host[part] || {};
  71. host = host[part];
  72. }
  73. host[last] = modules[key];
  74. }
  75. },
  76. exports = factory(root, _define, _require),
  77. origin;
  78. // exports every module.
  79. exportsTo(exports);
  80. if (typeof module === 'object' && typeof module.exports === 'object') {
  81. // For CommonJS and CommonJS-like environments where a proper window is present,
  82. module.exports = exports;
  83. } else if (typeof define === 'function' && define.amd) {
  84. // Allow using this built library as an AMD module
  85. // in another project. That other project will only
  86. // see this AMD call, not the internal modules in
  87. // the closure below.
  88. define([], exports);
  89. } else {
  90. // Browser globals case. Just assign the
  91. // result to a property on the global.
  92. origin = root.WebUploader;
  93. root.WebUploader = exports;
  94. root.WebUploader.noConflict = function () {
  95. root.WebUploader = origin;
  96. };
  97. }
  98. })(this, function (window, define, require) {
  99. /**
  100. * @fileOverview jQuery or Zepto
  101. */
  102. define('dollar-third', [], function () {
  103. return window.jQuery || window.Zepto;
  104. });
  105. /**
  106. * @fileOverview Dom 操作相关
  107. */
  108. define('dollar', [
  109. 'dollar-third'
  110. ], function (_) {
  111. return _;
  112. });
  113. /**
  114. * @fileOverview 使用jQuery的Promise
  115. */
  116. define('promise-third', [
  117. 'dollar'
  118. ], function ($) {
  119. return {
  120. Deferred: $.Deferred,
  121. when: $.when,
  122. isPromise: function (anything) {
  123. return anything && typeof anything.then === 'function';
  124. }
  125. };
  126. });
  127. /**
  128. * @fileOverview Promise/A+
  129. */
  130. define('promise', [
  131. 'promise-third'
  132. ], function (_) {
  133. return _;
  134. });
  135. /**
  136. * @fileOverview 基础类方法。
  137. */
  138. /**
  139. * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。
  140. *
  141. * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id.
  142. * 默认module id该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如:
  143. *
  144. * * module `base`:WebUploader.Base
  145. * * module `file`: WebUploader.File
  146. * * module `lib/dnd`: WebUploader.Lib.Dnd
  147. * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd
  148. *
  149. *
  150. * 以下文档将可能省略`WebUploader`前缀。
  151. * @module WebUploader
  152. * @title WebUploader API文档
  153. */
  154. define('base', [
  155. 'dollar',
  156. 'promise'
  157. ], function ($, promise) {
  158. var noop = function () {
  159. },
  160. call = Function.call;
  161. // http://jsperf.com/uncurrythis
  162. // 反科里化
  163. function uncurryThis(fn) {
  164. return function () {
  165. return call.apply(fn, arguments);
  166. };
  167. }
  168. function bindFn(fn, context) {
  169. return function () {
  170. return fn.apply(context, arguments);
  171. };
  172. }
  173. function createObject(proto) {
  174. var f;
  175. if (Object.create) {
  176. return Object.create(proto);
  177. } else {
  178. f = function () {
  179. };
  180. f.prototype = proto;
  181. return new f();
  182. }
  183. }
  184. /**
  185. * 基础类,提供一些简单常用的方法。
  186. * @class Base
  187. */
  188. return {
  189. /**
  190. * @property {String} version 当前版本号。
  191. */
  192. version: '0.1.2',
  193. /**
  194. * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。
  195. */
  196. $: $,
  197. Deferred: promise.Deferred,
  198. isPromise: promise.isPromise,
  199. when: promise.when,
  200. /**
  201. * @description 简单的浏览器检查结果。
  202. *
  203. * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。
  204. * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。
  205. * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+**
  206. * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。
  207. * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。
  208. * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。
  209. *
  210. * @property {Object} [browser]
  211. */
  212. browser: (function (ua) {
  213. var ret = {},
  214. webkit = ua.match(/WebKit\/([\d.]+)/),
  215. chrome = ua.match(/Chrome\/([\d.]+)/) ||
  216. ua.match(/CriOS\/([\d.]+)/),
  217. ie = ua.match(/MSIE\s([\d\.]+)/) ||
  218. ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i),
  219. firefox = ua.match(/Firefox\/([\d.]+)/),
  220. safari = ua.match(/Safari\/([\d.]+)/),
  221. opera = ua.match(/OPR\/([\d.]+)/);
  222. webkit && (ret.webkit = parseFloat(webkit[1]));
  223. chrome && (ret.chrome = parseFloat(chrome[1]));
  224. ie && (ret.ie = parseFloat(ie[1]));
  225. firefox && (ret.firefox = parseFloat(firefox[1]));
  226. safari && (ret.safari = parseFloat(safari[1]));
  227. opera && (ret.opera = parseFloat(opera[1]));
  228. return ret;
  229. })(navigator.userAgent),
  230. /**
  231. * @description 操作系统检查结果。
  232. *
  233. * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。
  234. * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。
  235. * @property {Object} [os]
  236. */
  237. os: (function (ua) {
  238. var ret = {},
  239. // osx = !!ua.match( /\(Macintosh\; Intel / ),
  240. android = ua.match(/(?:Android);?[\s\/]+([\d.]+)?/),
  241. ios = ua.match(/(?:iPad|iPod|iPhone).*OS\s([\d_]+)/);
  242. // osx && (ret.osx = true);
  243. android && (ret.android = parseFloat(android[1]));
  244. ios && (ret.ios = parseFloat(ios[1].replace(/_/g, '.')));
  245. return ret;
  246. })(navigator.userAgent),
  247. /**
  248. * 实现类与类之间的继承。
  249. * @method inherits
  250. * @grammar Base.inherits( super ) => child
  251. * @grammar Base.inherits( super, protos ) => child
  252. * @grammar Base.inherits( super, protos, statics ) => child
  253. * @param {Class} super 父类
  254. * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。
  255. * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。
  256. * @param {Object} [statics] 静态属性或方法。
  257. * @return {Class} 返回子类。
  258. * @example
  259. * function Person() {
  260. * console.log( 'Super' );
  261. * }
  262. * Person.prototype.hello = function() {
  263. * console.log( 'hello' );
  264. * };
  265. *
  266. * var Manager = Base.inherits( Person, {
  267. * world: function() {
  268. * console.log( 'World' );
  269. * }
  270. * });
  271. *
  272. * // 因为没有指定构造器,父类的构造器将会执行。
  273. * var instance = new Manager(); // => Super
  274. *
  275. * // 继承子父类的方法
  276. * instance.hello(); // => hello
  277. * instance.world(); // => World
  278. *
  279. * // 子类的__super__属性指向父类
  280. * console.log( Manager.__super__ === Person ); // => true
  281. */
  282. inherits: function (Super, protos, staticProtos) {
  283. var child;
  284. if (typeof protos === 'function') {
  285. child = protos;
  286. protos = null;
  287. } else if (protos && protos.hasOwnProperty('constructor')) {
  288. child = protos.constructor;
  289. } else {
  290. child = function () {
  291. return Super.apply(this, arguments);
  292. };
  293. }
  294. // 复制静态方法
  295. $.extend(true, child, Super, staticProtos || {});
  296. /* jshint camelcase: false */
  297. // 让子类的__super__属性指向父类。
  298. child.__super__ = Super.prototype;
  299. // 构建原型,添加原型方法或属性。
  300. // 暂时用Object.create实现。
  301. child.prototype = createObject(Super.prototype);
  302. protos && $.extend(true, child.prototype, protos);
  303. return child;
  304. },
  305. /**
  306. * 一个不做任何事情的方法。可以用来赋值给默认的callback.
  307. * @method noop
  308. */
  309. noop: noop,
  310. /**
  311. * 返回一个新的方法,此方法将已指定的`context`来执行。
  312. * @grammar Base.bindFn( fn, context ) => Function
  313. * @method bindFn
  314. * @example
  315. * var doSomething = function() {
  316. * console.log( this.name );
  317. * },
  318. * obj = {
  319. * name: 'Object Name'
  320. * },
  321. * aliasFn = Base.bind( doSomething, obj );
  322. *
  323. * aliasFn(); // => Object Name
  324. *
  325. */
  326. bindFn: bindFn,
  327. /**
  328. * 引用Console.log如果存在的话,否则引用一个[空函数loop](#WebUploader:Base.log)。
  329. * @grammar Base.log( args... ) => undefined
  330. * @method log
  331. */
  332. log: (function () {
  333. if (window.console) {
  334. return bindFn(console.log, console);
  335. }
  336. return noop;
  337. })(),
  338. nextTick: (function () {
  339. return function (cb) {
  340. setTimeout(cb, 1);
  341. };
  342. // @bug 当浏览器不在当前窗口时就停了。
  343. // var next = window.requestAnimationFrame ||
  344. // window.webkitRequestAnimationFrame ||
  345. // window.mozRequestAnimationFrame ||
  346. // function( cb ) {
  347. // window.setTimeout( cb, 1000 / 60 );
  348. // };
  349. // // fix: Uncaught TypeError: Illegal invocation
  350. // return bindFn( next, window );
  351. })(),
  352. /**
  353. * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。
  354. * 将用来将非数组对象转化成数组对象。
  355. * @grammar Base.slice( target, start[, end] ) => Array
  356. * @method slice
  357. * @example
  358. * function doSomthing() {
  359. * var args = Base.slice( arguments, 1 );
  360. * console.log( args );
  361. * }
  362. *
  363. * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"]
  364. */
  365. slice: uncurryThis([].slice),
  366. /**
  367. * 生成唯一的ID
  368. * @method guid
  369. * @grammar Base.guid() => String
  370. * @grammar Base.guid( prefx ) => String
  371. */
  372. guid: (function () {
  373. var counter = 0;
  374. return function (prefix) {
  375. var guid = (+new Date()).toString(32),
  376. i = 0;
  377. for (; i < 5; i++) {
  378. guid += Math.floor(Math.random() * 65535).toString(32);
  379. }
  380. return (prefix || 'wu_') + guid + (counter++).toString(32);
  381. };
  382. })(),
  383. /**
  384. * 格式化文件大小, 输出成带单位的字符串
  385. * @method formatSize
  386. * @grammar Base.formatSize( size ) => String
  387. * @grammar Base.formatSize( size, pointLength ) => String
  388. * @grammar Base.formatSize( size, pointLength, units ) => String
  389. * @param {Number} size 文件大小
  390. * @param {Number} [pointLength=2] 精确到的小数点数。
  391. * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K.
  392. * @example
  393. * console.log( Base.formatSize( 100 ) ); // => 100B
  394. * console.log( Base.formatSize( 1024 ) ); // => 1.00K
  395. * console.log( Base.formatSize( 1024, 0 ) ); // => 1K
  396. * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M
  397. * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G
  398. * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB
  399. */
  400. formatSize: function (size, pointLength, units) {
  401. var unit;
  402. units = units || ['B', 'K', 'M', 'G', 'TB'];
  403. while ((unit = units.shift()) && size > 1024) {
  404. size = size / 1024;
  405. }
  406. return (unit === 'B' ? size : size.toFixed(pointLength || 2)) +
  407. unit;
  408. }
  409. };
  410. });
  411. /**
  412. * 事件处理类,可以独立使用,也可以扩展给对象使用。
  413. * @fileOverview Mediator
  414. */
  415. define('mediator', [
  416. 'base'
  417. ], function (Base) {
  418. var $ = Base.$,
  419. slice = [].slice,
  420. separator = /\s+/,
  421. protos;
  422. // 根据条件过滤出事件handlers.
  423. function findHandlers(arr, name, callback, context) {
  424. return $.grep(arr, function (handler) {
  425. return handler &&
  426. (!name || handler.e === name) &&
  427. (!callback || handler.cb === callback ||
  428. handler.cb._cb === callback) &&
  429. (!context || handler.ctx === context);
  430. });
  431. }
  432. function eachEvent(events, callback, iterator) {
  433. // 不支持对象,只支持多个event用空格隔开
  434. $.each((events || '').split(separator), function (_, key) {
  435. iterator(key, callback);
  436. });
  437. }
  438. function triggerHanders(events, args) {
  439. var stoped = false,
  440. i = -1,
  441. len = events.length,
  442. handler;
  443. while (++i < len) {
  444. handler = events[i];
  445. if (handler.cb.apply(handler.ctx2, args) === false) {
  446. stoped = true;
  447. break;
  448. }
  449. }
  450. return !stoped;
  451. }
  452. protos = {
  453. /**
  454. * 绑定事件。
  455. *
  456. * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如
  457. * ```javascript
  458. * var obj = {};
  459. *
  460. * // 使得obj有事件行为
  461. * Mediator.installTo( obj );
  462. *
  463. * obj.on( 'testa', function( arg1, arg2 ) {
  464. * console.log( arg1, arg2 ); // => 'arg1', 'arg2'
  465. * });
  466. *
  467. * obj.trigger( 'testa', 'arg1', 'arg2' );
  468. * ```
  469. *
  470. * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。
  471. * 切会影响到`trigger`方法的返回值,为`false`。
  472. *
  473. * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处,
  474. * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。
  475. * ```javascript
  476. * obj.on( 'all', function( type, arg1, arg2 ) {
  477. * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2'
  478. * });
  479. * ```
  480. *
  481. * @method on
  482. * @grammar on( name, callback[, context] ) => self
  483. * @param {String} name 事件名,支持多个事件用空格隔开
  484. * @param {Function} callback 事件处理器
  485. * @param {Object} [context] 事件处理器的上下文。
  486. * @return {self} 返回自身,方便链式
  487. * @chainable
  488. * @class Mediator
  489. */
  490. on: function (name, callback, context) {
  491. var me = this,
  492. set;
  493. if (!callback) {
  494. return this;
  495. }
  496. set = this._events || (this._events = []);
  497. eachEvent(name, callback, function (name, callback) {
  498. var handler = {e: name};
  499. handler.cb = callback;
  500. handler.ctx = context;
  501. handler.ctx2 = context || me;
  502. handler.id = set.length;
  503. set.push(handler);
  504. });
  505. return this;
  506. },
  507. /**
  508. * 绑定事件,且当handler执行完后,自动解除绑定。
  509. * @method once
  510. * @grammar once( name, callback[, context] ) => self
  511. * @param {String} name 事件名
  512. * @param {Function} callback 事件处理器
  513. * @param {Object} [context] 事件处理器的上下文。
  514. * @return {self} 返回自身,方便链式
  515. * @chainable
  516. */
  517. once: function (name, callback, context) {
  518. var me = this;
  519. if (!callback) {
  520. return me;
  521. }
  522. eachEvent(name, callback, function (name, callback) {
  523. var once = function () {
  524. me.off(name, once);
  525. return callback.apply(context || me, arguments);
  526. };
  527. once._cb = callback;
  528. me.on(name, once, context);
  529. });
  530. return me;
  531. },
  532. /**
  533. * 解除事件绑定
  534. * @method off
  535. * @grammar off( [name[, callback[, context] ] ] ) => self
  536. * @param {String} [name] 事件名
  537. * @param {Function} [callback] 事件处理器
  538. * @param {Object} [context] 事件处理器的上下文。
  539. * @return {self} 返回自身,方便链式
  540. * @chainable
  541. */
  542. off: function (name, cb, ctx) {
  543. var events = this._events;
  544. if (!events) {
  545. return this;
  546. }
  547. if (!name && !cb && !ctx) {
  548. this._events = [];
  549. return this;
  550. }
  551. eachEvent(name, cb, function (name, cb) {
  552. $.each(findHandlers(events, name, cb, ctx), function () {
  553. delete events[this.id];
  554. });
  555. });
  556. return this;
  557. },
  558. /**
  559. * 触发事件
  560. * @method trigger
  561. * @grammar trigger( name[, args...] ) => self
  562. * @param {String} type 事件名
  563. * @param {*} [...] 任意参数
  564. * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true
  565. */
  566. trigger: function (type) {
  567. var args, events, allEvents;
  568. if (!this._events || !type) {
  569. return this;
  570. }
  571. args = slice.call(arguments, 1);
  572. events = findHandlers(this._events, type);
  573. allEvents = findHandlers(this._events, 'all');
  574. return triggerHanders(events, args) &&
  575. triggerHanders(allEvents, arguments);
  576. }
  577. };
  578. /**
  579. * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。
  580. * 主要目的是负责模块与模块之间的合作,降低耦合度。
  581. *
  582. * @class Mediator
  583. */
  584. return $.extend({
  585. /**
  586. * 可以通过这个接口,使任何对象具备事件功能。
  587. * @method installTo
  588. * @param {Object} obj 需要具备事件行为的对象。
  589. * @return {Object} 返回obj.
  590. */
  591. installTo: function (obj) {
  592. return $.extend(obj, protos);
  593. }
  594. }, protos);
  595. });
  596. /**
  597. * @fileOverview Uploader上传类
  598. */
  599. define('uploader', [
  600. 'base',
  601. 'mediator'
  602. ], function (Base, Mediator) {
  603. var $ = Base.$;
  604. /**
  605. * 上传入口类。
  606. * @class Uploader
  607. * @constructor
  608. * @grammar new Uploader( opts ) => Uploader
  609. * @example
  610. * var uploader = WebUploader.Uploader({
  611. * swf: 'path_of_swf/Uploader.swf',
  612. *
  613. * // 开起分片上传。
  614. * chunked: true
  615. * });
  616. */
  617. function Uploader(opts) {
  618. this.options = $.extend(true, {}, Uploader.options, opts);
  619. this._init(this.options);
  620. }
  621. // default Options
  622. // widgets中有相应扩展
  623. Uploader.options = {};
  624. Mediator.installTo(Uploader.prototype);
  625. // 批量添加纯命令式方法。
  626. $.each({
  627. upload: 'start-upload',
  628. stop: 'stop-upload',
  629. getFile: 'get-file',
  630. getFiles: 'get-files',
  631. addFile: 'add-file',
  632. addFiles: 'add-file',
  633. sort: 'sort-files',
  634. removeFile: 'remove-file',
  635. skipFile: 'skip-file',
  636. retry: 'retry',
  637. isInProgress: 'is-in-progress',
  638. makeThumb: 'make-thumb',
  639. getDimension: 'get-dimension',
  640. addButton: 'add-btn',
  641. getRuntimeType: 'get-runtime-type',
  642. refresh: 'refresh',
  643. disable: 'disable',
  644. enable: 'enable',
  645. reset: 'reset'
  646. }, function (fn, command) {
  647. Uploader.prototype[fn] = function () {
  648. return this.request(command, arguments);
  649. };
  650. });
  651. $.extend(Uploader.prototype, {
  652. state: 'pending',
  653. _init: function (opts) {
  654. var me = this;
  655. me.request('init', opts, function () {
  656. me.state = 'ready';
  657. me.trigger('ready');
  658. });
  659. },
  660. /**
  661. * 获取或者设置Uploader配置项。
  662. * @method option
  663. * @grammar option( key ) => *
  664. * @grammar option( key, val ) => self
  665. * @example
  666. *
  667. * // 初始状态图片上传前不会压缩
  668. * var uploader = new WebUploader.Uploader({
  669. * resize: null;
  670. * });
  671. *
  672. * // 修改后图片上传前,尝试将图片压缩到1600 * 1600
  673. * uploader.options( 'resize', {
  674. * width: 1600,
  675. * height: 1600
  676. * });
  677. */
  678. option: function (key, val) {
  679. var opts = this.options;
  680. // setter
  681. if (arguments.length > 1) {
  682. if ($.isPlainObject(val) &&
  683. $.isPlainObject(opts[key])) {
  684. $.extend(opts[key], val);
  685. } else {
  686. opts[key] = val;
  687. }
  688. } else { // getter
  689. return key ? opts[key] : opts;
  690. }
  691. },
  692. /**
  693. * 获取文件统计信息。返回一个包含一下信息的对象。
  694. * * `successNum` 上传成功的文件数
  695. * * `uploadFailNum` 上传失败的文件数
  696. * * `cancelNum` 被删除的文件数
  697. * * `invalidNum` 无效的文件数
  698. * * `queueNum` 还在队列中的文件数
  699. * @method getStats
  700. * @grammar getStats() => Object
  701. */
  702. getStats: function () {
  703. // return this._mgr.getStats.apply( this._mgr, arguments );
  704. var stats = this.request('get-stats');
  705. return {
  706. successNum: stats.numOfSuccess,
  707. // who care?
  708. // queueFailNum: 0,
  709. cancelNum: stats.numOfCancel,
  710. invalidNum: stats.numOfInvalid,
  711. uploadFailNum: stats.numOfUploadFailed,
  712. queueNum: stats.numOfQueue
  713. };
  714. },
  715. // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器
  716. trigger: function (type/*, args...*/) {
  717. var args = [].slice.call(arguments, 1),
  718. opts = this.options,
  719. name = 'on' + type.substring(0, 1).toUpperCase() +
  720. type.substring(1);
  721. if (
  722. // 调用通过on方法注册的handler.
  723. Mediator.trigger.apply(this, arguments) === false ||
  724. // 调用opts.onEvent
  725. $.isFunction(opts[name]) &&
  726. opts[name].apply(this, args) === false ||
  727. // 调用this.onEvent
  728. $.isFunction(this[name]) &&
  729. this[name].apply(this, args) === false ||
  730. // 广播所有uploader的事件。
  731. Mediator.trigger.apply(Mediator,
  732. [this, type].concat(args)) === false) {
  733. return false;
  734. }
  735. return true;
  736. },
  737. // widgets/widget.js将补充此方法的详细文档。
  738. request: Base.noop
  739. });
  740. /**
  741. * 创建Uploader实例,等同于new Uploader( opts );
  742. * @method create
  743. * @class Base
  744. * @static
  745. * @grammar Base.create( opts ) => Uploader
  746. */
  747. Base.create = Uploader.create = function (opts) {
  748. return new Uploader(opts);
  749. };
  750. // 暴露Uploader,可以通过它来扩展业务逻辑。
  751. Base.Uploader = Uploader;
  752. return Uploader;
  753. });
  754. /**
  755. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  756. */
  757. define('runtime/runtime', [
  758. 'base',
  759. 'mediator'
  760. ], function (Base, Mediator) {
  761. var $ = Base.$,
  762. factories = {},
  763. // 获取对象的第一个key
  764. getFirstKey = function (obj) {
  765. for (var key in obj) {
  766. if (obj.hasOwnProperty(key)) {
  767. return key;
  768. }
  769. }
  770. return null;
  771. };
  772. // 接口类。
  773. function Runtime(options) {
  774. this.options = $.extend({
  775. container: document.body
  776. }, options);
  777. this.uid = Base.guid('rt_');
  778. }
  779. $.extend(Runtime.prototype, {
  780. getContainer: function () {
  781. var opts = this.options,
  782. parent, container;
  783. if (this._container) {
  784. return this._container;
  785. }
  786. parent = $(opts.container || document.body);
  787. container = $(document.createElement('div'));
  788. container.attr('id', 'rt_' + this.uid);
  789. container.css({
  790. position: 'absolute',
  791. top: '0px',
  792. left: '0px',
  793. width: '1px',
  794. height: '1px',
  795. overflow: 'hidden'
  796. });
  797. parent.append(container);
  798. parent.addClass('webuploader-container');
  799. this._container = container;
  800. return container;
  801. },
  802. init: Base.noop,
  803. exec: Base.noop,
  804. destroy: function () {
  805. if (this._container) {
  806. this._container.parentNode.removeChild(this.__container);
  807. }
  808. this.off();
  809. }
  810. });
  811. Runtime.orders = 'html5,flash';
  812. /**
  813. * 添加Runtime实现。
  814. * @param {String} type 类型
  815. * @param {Runtime} factory 具体Runtime实现。
  816. */
  817. Runtime.addRuntime = function (type, factory) {
  818. factories[type] = factory;
  819. };
  820. Runtime.hasRuntime = function (type) {
  821. return !!(type ? factories[type] : getFirstKey(factories));
  822. };
  823. Runtime.create = function (opts, orders) {
  824. var type, runtime;
  825. orders = orders || Runtime.orders;
  826. $.each(orders.split(/\s*,\s*/g), function () {
  827. if (factories[this]) {
  828. type = this;
  829. return false;
  830. }
  831. });
  832. type = type || getFirstKey(factories);
  833. if (!type) {
  834. throw new Error('Runtime Error');
  835. }
  836. runtime = new factories[type](opts);
  837. return runtime;
  838. };
  839. Mediator.installTo(Runtime.prototype);
  840. return Runtime;
  841. });
  842. /**
  843. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  844. */
  845. define('runtime/client', [
  846. 'base',
  847. 'mediator',
  848. 'runtime/runtime'
  849. ], function (Base, Mediator, Runtime) {
  850. var cache;
  851. cache = (function () {
  852. var obj = {};
  853. return {
  854. add: function (runtime) {
  855. obj[runtime.uid] = runtime;
  856. },
  857. get: function (ruid, standalone) {
  858. var i;
  859. if (ruid) {
  860. return obj[ruid];
  861. }
  862. for (i in obj) {
  863. // 有些类型不能重用,比如filepicker.
  864. if (standalone && obj[i].__standalone) {
  865. continue;
  866. }
  867. return obj[i];
  868. }
  869. return null;
  870. },
  871. remove: function (runtime) {
  872. delete obj[runtime.uid];
  873. }
  874. };
  875. })();
  876. function RuntimeClient(component, standalone) {
  877. var deferred = Base.Deferred(),
  878. runtime;
  879. this.uid = Base.guid('client_');
  880. // 允许runtime没有初始化之前,注册一些方法在初始化后执行。
  881. this.runtimeReady = function (cb) {
  882. return deferred.done(cb);
  883. };
  884. this.connectRuntime = function (opts, cb) {
  885. // already connected.
  886. if (runtime) {
  887. throw new Error('already connected!');
  888. }
  889. deferred.done(cb);
  890. if (typeof opts === 'string' && cache.get(opts)) {
  891. runtime = cache.get(opts);
  892. }
  893. // 像filePicker只能独立存在,不能公用。
  894. runtime = runtime || cache.get(null, standalone);
  895. // 需要创建
  896. if (!runtime) {
  897. runtime = Runtime.create(opts, opts.runtimeOrder);
  898. runtime.__promise = deferred.promise();
  899. runtime.once('ready', deferred.resolve);
  900. runtime.init();
  901. cache.add(runtime);
  902. runtime.__client = 1;
  903. } else {
  904. // 来自cache
  905. Base.$.extend(runtime.options, opts);
  906. runtime.__promise.then(deferred.resolve);
  907. runtime.__client++;
  908. }
  909. standalone && (runtime.__standalone = standalone);
  910. return runtime;
  911. };
  912. this.getRuntime = function () {
  913. return runtime;
  914. };
  915. this.disconnectRuntime = function () {
  916. if (!runtime) {
  917. return;
  918. }
  919. runtime.__client--;
  920. if (runtime.__client <= 0) {
  921. cache.remove(runtime);
  922. delete runtime.__promise;
  923. runtime.destroy();
  924. }
  925. runtime = null;
  926. };
  927. this.exec = function () {
  928. if (!runtime) {
  929. return;
  930. }
  931. var args = Base.slice(arguments);
  932. component && args.unshift(component);
  933. return runtime.exec.apply(this, args);
  934. };
  935. this.getRuid = function () {
  936. return runtime && runtime.uid;
  937. };
  938. this.destroy = (function (destroy) {
  939. return function () {
  940. destroy && destroy.apply(this, arguments);
  941. this.trigger('destroy');
  942. this.off();
  943. this.exec('destroy');
  944. this.disconnectRuntime();
  945. };
  946. })(this.destroy);
  947. }
  948. Mediator.installTo(RuntimeClient.prototype);
  949. return RuntimeClient;
  950. });
  951. /**
  952. * @fileOverview 错误信息
  953. */
  954. define('lib/dnd', [
  955. 'base',
  956. 'mediator',
  957. 'runtime/client'
  958. ], function (Base, Mediator, RuntimeClent) {
  959. var $ = Base.$;
  960. function DragAndDrop(opts) {
  961. opts = this.options = $.extend({}, DragAndDrop.options, opts);
  962. opts.container = $(opts.container);
  963. if (!opts.container.length) {
  964. return;
  965. }
  966. RuntimeClent.call(this, 'DragAndDrop');
  967. }
  968. DragAndDrop.options = {
  969. accept: null,
  970. disableGlobalDnd: false
  971. };
  972. Base.inherits(RuntimeClent, {
  973. constructor: DragAndDrop,
  974. init: function () {
  975. var me = this;
  976. me.connectRuntime(me.options, function () {
  977. me.exec('init');
  978. me.trigger('ready');
  979. });
  980. },
  981. destroy: function () {
  982. this.disconnectRuntime();
  983. }
  984. });
  985. Mediator.installTo(DragAndDrop.prototype);
  986. return DragAndDrop;
  987. });
  988. /**
  989. * @fileOverview 组件基类。
  990. */
  991. define('widgets/widget', [
  992. 'base',
  993. 'uploader'
  994. ], function (Base, Uploader) {
  995. var $ = Base.$,
  996. _init = Uploader.prototype._init,
  997. IGNORE = {},
  998. widgetClass = [];
  999. function isArrayLike(obj) {
  1000. if (!obj) {
  1001. return false;
  1002. }
  1003. var length = obj.length,
  1004. type = $.type(obj);
  1005. if (obj.nodeType === 1 && length) {
  1006. return true;
  1007. }
  1008. return type === 'array' || type !== 'function' && type !== 'string' &&
  1009. (length === 0 || typeof length === 'number' && length > 0 &&
  1010. (length - 1) in obj);
  1011. }
  1012. function Widget(uploader) {
  1013. this.owner = uploader;
  1014. this.options = uploader.options;
  1015. }
  1016. $.extend(Widget.prototype, {
  1017. init: Base.noop,
  1018. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1019. // widget直接无法监听事件,事件只能通过uploader来传递
  1020. invoke: function (apiName, args) {
  1021. /*
  1022. {
  1023. 'make-thumb': 'makeThumb'
  1024. }
  1025. */
  1026. var map = this.responseMap;
  1027. // 如果无API响应声明则忽略
  1028. if (!map || !(apiName in map) || !(map[apiName] in this) ||
  1029. !$.isFunction(this[map[apiName]])) {
  1030. return IGNORE;
  1031. }
  1032. return this[map[apiName]].apply(this, args);
  1033. },
  1034. /**
  1035. * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
  1036. * @method request
  1037. * @grammar request( command, args ) => * | Promise
  1038. * @grammar request( command, args, callback ) => Promise
  1039. * @for Uploader
  1040. */
  1041. request: function () {
  1042. return this.owner.request.apply(this.owner, arguments);
  1043. }
  1044. });
  1045. // 扩展Uploader.
  1046. $.extend(Uploader.prototype, {
  1047. // 覆写_init用来初始化widgets
  1048. _init: function () {
  1049. var me = this,
  1050. widgets = me._widgets = [];
  1051. $.each(widgetClass, function (_, klass) {
  1052. widgets.push(new klass(me));
  1053. });
  1054. return _init.apply(me, arguments);
  1055. },
  1056. request: function (apiName, args, callback) {
  1057. var i = 0,
  1058. widgets = this._widgets,
  1059. len = widgets.length,
  1060. rlts = [],
  1061. dfds = [],
  1062. widget, rlt, promise, key;
  1063. args = isArrayLike(args) ? args : [args];
  1064. for (; i < len; i++) {
  1065. widget = widgets[i];
  1066. rlt = widget.invoke(apiName, args);
  1067. if (rlt !== IGNORE) {
  1068. // Deferred对象
  1069. if (Base.isPromise(rlt)) {
  1070. dfds.push(rlt);
  1071. } else {
  1072. rlts.push(rlt);
  1073. }
  1074. }
  1075. }
  1076. // 如果有callback,则用异步方式。
  1077. if (callback || dfds.length) {
  1078. promise = Base.when.apply(Base, dfds);
  1079. key = promise.pipe ? 'pipe' : 'then';
  1080. // 很重要不能删除。删除了会死循环。
  1081. // 保证执行顺序。让callback总是在下一个tick中执行。
  1082. return promise[key](function () {
  1083. var deferred = Base.Deferred(),
  1084. args = arguments;
  1085. setTimeout(function () {
  1086. deferred.resolve.apply(deferred, args);
  1087. }, 1);
  1088. return deferred.promise();
  1089. })[key](callback || Base.noop);
  1090. } else {
  1091. return rlts[0];
  1092. }
  1093. }
  1094. });
  1095. /**
  1096. * 添加组件
  1097. * @param {object} widgetProto 组件原型,构造函数通过constructor属性定义
  1098. * @param {object} responseMap API名称与函数实现的映射
  1099. * @example
  1100. * Uploader.register( {
  1101. * init: function( options ) {},
  1102. * makeThumb: function() {}
  1103. * }, {
  1104. * 'make-thumb': 'makeThumb'
  1105. * } );
  1106. */
  1107. Uploader.register = Widget.register = function (responseMap, widgetProto) {
  1108. var map = {init: 'init'},
  1109. klass;
  1110. if (arguments.length === 1) {
  1111. widgetProto = responseMap;
  1112. widgetProto.responseMap = map;
  1113. } else {
  1114. widgetProto.responseMap = $.extend(map, responseMap);
  1115. }
  1116. klass = Base.inherits(Widget, widgetProto);
  1117. widgetClass.push(klass);
  1118. return klass;
  1119. };
  1120. return Widget;
  1121. });
  1122. /**
  1123. * @fileOverview DragAndDrop Widget。
  1124. */
  1125. define('widgets/filednd', [
  1126. 'base',
  1127. 'uploader',
  1128. 'lib/dnd',
  1129. 'widgets/widget'
  1130. ], function (Base, Uploader, Dnd) {
  1131. var $ = Base.$;
  1132. Uploader.options.dnd = '';
  1133. /**
  1134. * @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
  1135. * @namespace options
  1136. * @for Uploader
  1137. */
  1138. /**
  1139. * @event dndAccept
  1140. * @param {DataTransferItemList} items DataTransferItem
  1141. * @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
  1142. * @for Uploader
  1143. */
  1144. return Uploader.register({
  1145. init: function (opts) {
  1146. if (!opts.dnd ||
  1147. this.request('predict-runtime-type') !== 'html5') {
  1148. return;
  1149. }
  1150. var me = this,
  1151. deferred = Base.Deferred(),
  1152. options = $.extend({}, {
  1153. disableGlobalDnd: opts.disableGlobalDnd,
  1154. container: opts.dnd,
  1155. accept: opts.accept
  1156. }),
  1157. dnd;
  1158. dnd = new Dnd(options);
  1159. dnd.once('ready', deferred.resolve);
  1160. dnd.on('drop', function (files) {
  1161. me.request('add-file', [files]);
  1162. });
  1163. // 检测文件是否全部允许添加。
  1164. dnd.on('accept', function (items) {
  1165. return me.owner.trigger('dndAccept', items);
  1166. });
  1167. dnd.init();
  1168. return deferred.promise();
  1169. }
  1170. });
  1171. });
  1172. /**
  1173. * @fileOverview 错误信息
  1174. */
  1175. define('lib/filepaste', [
  1176. 'base',
  1177. 'mediator',
  1178. 'runtime/client'
  1179. ], function (Base, Mediator, RuntimeClent) {
  1180. var $ = Base.$;
  1181. function FilePaste(opts) {
  1182. opts = this.options = $.extend({}, opts);
  1183. opts.container = $(opts.container || document.body);
  1184. RuntimeClent.call(this, 'FilePaste');
  1185. }
  1186. Base.inherits(RuntimeClent, {
  1187. constructor: FilePaste,
  1188. init: function () {
  1189. var me = this;
  1190. me.connectRuntime(me.options, function () {
  1191. me.exec('init');
  1192. me.trigger('ready');
  1193. });
  1194. },
  1195. destroy: function () {
  1196. this.exec('destroy');
  1197. this.disconnectRuntime();
  1198. this.off();
  1199. }
  1200. });
  1201. Mediator.installTo(FilePaste.prototype);
  1202. return FilePaste;
  1203. });
  1204. /**
  1205. * @fileOverview 组件基类。
  1206. */
  1207. define('widgets/filepaste', [
  1208. 'base',
  1209. 'uploader',
  1210. 'lib/filepaste',
  1211. 'widgets/widget'
  1212. ], function (Base, Uploader, FilePaste) {
  1213. var $ = Base.$;
  1214. /**
  1215. * @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
  1216. * @namespace options
  1217. * @for Uploader
  1218. */
  1219. return Uploader.register({
  1220. init: function (opts) {
  1221. if (!opts.paste ||
  1222. this.request('predict-runtime-type') !== 'html5') {
  1223. return;
  1224. }
  1225. var me = this,
  1226. deferred = Base.Deferred(),
  1227. options = $.extend({}, {
  1228. container: opts.paste,
  1229. accept: opts.accept
  1230. }),
  1231. paste;
  1232. paste = new FilePaste(options);
  1233. paste.once('ready', deferred.resolve);
  1234. paste.on('paste', function (files) {
  1235. me.owner.request('add-file', [files]);
  1236. });
  1237. paste.init();
  1238. return deferred.promise();
  1239. }
  1240. });
  1241. });
  1242. /**
  1243. * @fileOverview Blob
  1244. */
  1245. define('lib/blob', [
  1246. 'base',
  1247. 'runtime/client'
  1248. ], function (Base, RuntimeClient) {
  1249. function Blob(ruid, source) {
  1250. var me = this;
  1251. me.source = source;
  1252. me.ruid = ruid;
  1253. RuntimeClient.call(me, 'Blob');
  1254. this.uid = source.uid || this.uid;
  1255. this.type = source.type || '';
  1256. this.size = source.size || 0;
  1257. if (ruid) {
  1258. me.connectRuntime(ruid);
  1259. }
  1260. }
  1261. Base.inherits(RuntimeClient, {
  1262. constructor: Blob,
  1263. slice: function (start, end) {
  1264. return this.exec('slice', start, end);
  1265. },
  1266. getSource: function () {
  1267. return this.source;
  1268. }
  1269. });
  1270. return Blob;
  1271. });
  1272. /**
  1273. * 为了统一化Flash的File和HTML5的File而存在。
  1274. * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。
  1275. * @fileOverview File
  1276. */
  1277. define('lib/file', [
  1278. 'base',
  1279. 'lib/blob'
  1280. ], function (Base, Blob) {
  1281. var uid = 1,
  1282. rExt = /\.([^.]+)$/;
  1283. function File(ruid, file) {
  1284. var ext;
  1285. Blob.apply(this, arguments);
  1286. this.name = file.name || ('untitled' + uid++);
  1287. ext = rExt.exec(file.name) ? RegExp.$1.toLowerCase() : '';
  1288. // todo 支持其他类型文件的转换。
  1289. // 如果有mimetype, 但是文件名里面没有找出后缀规律
  1290. if (!ext && this.type) {
  1291. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec(this.type) ?
  1292. RegExp.$1.toLowerCase() : '';
  1293. this.name += '.' + ext;
  1294. }
  1295. // 如果没有指定mimetype, 但是知道文件后缀。
  1296. if (!this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf(ext)) {
  1297. this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext);
  1298. }
  1299. this.ext = ext;
  1300. this.lastModifiedDate = file.lastModifiedDate ||
  1301. (new Date()).toLocaleString();
  1302. }
  1303. return Base.inherits(Blob, File);
  1304. });
  1305. /**
  1306. * @fileOverview 错误信息
  1307. */
  1308. define('lib/filepicker', [
  1309. 'base',
  1310. 'runtime/client',
  1311. 'lib/file'
  1312. ], function (Base, RuntimeClent, File) {
  1313. var $ = Base.$;
  1314. function FilePicker(opts) {
  1315. opts = this.options = $.extend({}, FilePicker.options, opts);
  1316. opts.container = $(opts.id);
  1317. if (!opts.container.length) {
  1318. throw new Error('按钮指定错误');
  1319. }
  1320. opts.innerHTML = opts.innerHTML || opts.label ||
  1321. opts.container.html() || '';
  1322. opts.button = $(opts.button || document.createElement('div'));
  1323. opts.button.html(opts.innerHTML);
  1324. opts.container.html(opts.button);
  1325. RuntimeClent.call(this, 'FilePicker', true);
  1326. }
  1327. FilePicker.options = {
  1328. button: null,
  1329. container: null,
  1330. label: null,
  1331. innerHTML: null,
  1332. multiple: true,
  1333. accept: null,
  1334. name: 'file'
  1335. };
  1336. Base.inherits(RuntimeClent, {
  1337. constructor: FilePicker,
  1338. init: function () {
  1339. var me = this,
  1340. opts = me.options,
  1341. button = opts.button;
  1342. button.addClass('webuploader-pick');
  1343. me.on('all', function (type) {
  1344. var files;
  1345. switch (type) {
  1346. case 'mouseenter':
  1347. button.addClass('webuploader-pick-hover');
  1348. break;
  1349. case 'mouseleave':
  1350. button.removeClass('webuploader-pick-hover');
  1351. break;
  1352. case 'change':
  1353. files = me.exec('getFiles');
  1354. me.trigger('select', $.map(files, function (file) {
  1355. file = new File(me.getRuid(), file);
  1356. // 记录来源。
  1357. file._refer = opts.container;
  1358. return file;
  1359. }), opts.container);
  1360. break;
  1361. }
  1362. });
  1363. me.connectRuntime(opts, function () {
  1364. me.refresh();
  1365. me.exec('init', opts);
  1366. me.trigger('ready');
  1367. });
  1368. $(window).on('resize', function () {
  1369. me.refresh();
  1370. });
  1371. },
  1372. refresh: function () {
  1373. var shimContainer = this.getRuntime().getContainer(),
  1374. button = this.options.button,
  1375. width = button.outerWidth ?
  1376. button.outerWidth() : button.width(),
  1377. height = button.outerHeight ?
  1378. button.outerHeight() : button.height(),
  1379. pos = button.offset();
  1380. width && height && shimContainer.css({
  1381. bottom: 'auto',
  1382. right: 'auto',
  1383. width: width + 'px',
  1384. height: height + 'px'
  1385. }).offset(pos);
  1386. },
  1387. enable: function () {
  1388. var btn = this.options.button;
  1389. btn.removeClass('webuploader-pick-disable');
  1390. this.refresh();
  1391. },
  1392. disable: function () {
  1393. var btn = this.options.button;
  1394. this.getRuntime().getContainer().css({
  1395. top: '-99999px'
  1396. });
  1397. btn.addClass('webuploader-pick-disable');
  1398. },
  1399. destroy: function () {
  1400. if (this.runtime) {
  1401. this.exec('destroy');
  1402. this.disconnectRuntime();
  1403. }
  1404. }
  1405. });
  1406. return FilePicker;
  1407. });
  1408. /**
  1409. * @fileOverview 文件选择相关
  1410. */
  1411. define('widgets/filepicker', [
  1412. 'base',
  1413. 'uploader',
  1414. 'lib/filepicker',
  1415. 'widgets/widget'
  1416. ], function (Base, Uploader, FilePicker) {
  1417. var $ = Base.$;
  1418. $.extend(Uploader.options, {
  1419. /**
  1420. * @property {Selector | Object} [pick=undefined]
  1421. * @namespace options
  1422. * @for Uploader
  1423. * @description 指定选择文件的按钮容器,不指定则不创建按钮。
  1424. *
  1425. * * `id` {Seletor} 指定选择文件的按钮容器,不指定则不创建按钮。
  1426. * * `label` {String} 请采用 `innerHTML` 代替
  1427. * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
  1428. * * `multiple` {Boolean} 是否开起同时选择多个文件能力。
  1429. */
  1430. pick: null,
  1431. /**
  1432. * @property {Arroy} [accept=null]
  1433. * @namespace options
  1434. * @for Uploader
  1435. * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。
  1436. *
  1437. * * `title` {String} 文字描述
  1438. * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。
  1439. * * `mimeTypes` {String} 多个用逗号分割。
  1440. *
  1441. * 如:
  1442. *
  1443. * ```
  1444. * {
  1445. * title: 'Images',
  1446. * extensions: 'gif,jpg,jpeg,bmp,png',
  1447. * mimeTypes: 'image/*'
  1448. * }
  1449. * ```
  1450. */
  1451. accept: null/*{
  1452. title: 'Images',
  1453. extensions: 'gif,jpg,jpeg,bmp,png',
  1454. mimeTypes: 'image/*'
  1455. }*/
  1456. });
  1457. return Uploader.register({
  1458. 'add-btn': 'addButton',
  1459. refresh: 'refresh',
  1460. disable: 'disable',
  1461. enable: 'enable'
  1462. }, {
  1463. init: function (opts) {
  1464. this.pickers = [];
  1465. return opts.pick && this.addButton(opts.pick);
  1466. },
  1467. refresh: function () {
  1468. $.each(this.pickers, function () {
  1469. this.refresh();
  1470. });
  1471. },
  1472. /**
  1473. * @method addButton
  1474. * @for Uploader
  1475. * @grammar addButton( pick ) => Promise
  1476. * @description
  1477. * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。
  1478. * @example
  1479. * uploader.addButton({
  1480. * id: '#btnContainer',
  1481. * innerHTML: '选择文件'
  1482. * });
  1483. */
  1484. addButton: function (pick) {
  1485. var me = this,
  1486. opts = me.options,
  1487. accept = opts.accept,
  1488. options, picker, deferred;
  1489. if (!pick) {
  1490. return;
  1491. }
  1492. deferred = Base.Deferred();
  1493. $.isPlainObject(pick) || (pick = {
  1494. id: pick
  1495. });
  1496. options = $.extend({}, pick, {
  1497. accept: $.isPlainObject(accept) ? [accept] : accept,
  1498. swf: opts.swf,
  1499. runtimeOrder: opts.runtimeOrder
  1500. });
  1501. picker = new FilePicker(options);
  1502. picker.once('ready', deferred.resolve);
  1503. picker.on('select', function (files) {
  1504. me.owner.request('add-file', [files]);
  1505. });
  1506. picker.init();
  1507. this.pickers.push(picker);
  1508. return deferred.promise();
  1509. },
  1510. disable: function () {
  1511. $.each(this.pickers, function () {
  1512. this.disable();
  1513. });
  1514. },
  1515. enable: function () {
  1516. $.each(this.pickers, function () {
  1517. this.enable();
  1518. });
  1519. }
  1520. });
  1521. });
  1522. /**
  1523. * @fileOverview Image
  1524. */
  1525. define('lib/image', [
  1526. 'base',
  1527. 'runtime/client',
  1528. 'lib/blob'
  1529. ], function (Base, RuntimeClient, Blob) {
  1530. var $ = Base.$;
  1531. // 构造器。
  1532. function Image(opts) {
  1533. this.options = $.extend({}, Image.options, opts);
  1534. RuntimeClient.call(this, 'Image');
  1535. this.on('load', function () {
  1536. this._info = this.exec('info');
  1537. this._meta = this.exec('meta');
  1538. });
  1539. }
  1540. // 默认选项。
  1541. Image.options = {
  1542. // 默认的图片处理质量
  1543. quality: 90,
  1544. // 是否裁剪
  1545. crop: false,
  1546. // 是否保留头部信息
  1547. preserveHeaders: true,
  1548. // 是否允许放大。
  1549. allowMagnify: true
  1550. };
  1551. // 继承RuntimeClient.
  1552. Base.inherits(RuntimeClient, {
  1553. constructor: Image,
  1554. info: function (val) {
  1555. // setter
  1556. if (val) {
  1557. this._info = val;
  1558. return this;
  1559. }
  1560. // getter
  1561. return this._info;
  1562. },
  1563. meta: function (val) {
  1564. // setter
  1565. if (val) {
  1566. this._meta = val;
  1567. return this;
  1568. }
  1569. // getter
  1570. return this._meta;
  1571. },
  1572. loadFromBlob: function (blob) {
  1573. var me = this,
  1574. ruid = blob.getRuid();
  1575. this.connectRuntime(ruid, function () {
  1576. me.exec('init', me.options);
  1577. me.exec('loadFromBlob', blob);
  1578. });
  1579. },
  1580. resize: function () {
  1581. var args = Base.slice(arguments);
  1582. return this.exec.apply(this, ['resize'].concat(args));
  1583. },
  1584. getAsDataUrl: function (type) {
  1585. return this.exec('getAsDataUrl', type);
  1586. },
  1587. getAsBlob: function (type) {
  1588. var blob = this.exec('getAsBlob', type);
  1589. return new Blob(this.getRuid(), blob);
  1590. }
  1591. });
  1592. return Image;
  1593. });
  1594. /**
  1595. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1596. */
  1597. define('widgets/image', [
  1598. 'base',
  1599. 'uploader',
  1600. 'lib/image',
  1601. 'widgets/widget'
  1602. ], function (Base, Uploader, Image) {
  1603. var $ = Base.$,
  1604. throttle;
  1605. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1606. throttle = (function (max) {
  1607. var occupied = 0,
  1608. waiting = [],
  1609. tick = function () {
  1610. var item;
  1611. while (waiting.length && occupied < max) {
  1612. item = waiting.shift();
  1613. occupied += item[0];
  1614. item[1]();
  1615. }
  1616. };
  1617. return function (emiter, size, cb) {
  1618. waiting.push([size, cb]);
  1619. emiter.once('destroy', function () {
  1620. occupied -= size;
  1621. setTimeout(tick, 1);
  1622. });
  1623. setTimeout(tick, 1);
  1624. };
  1625. })(5 * 1024 * 1024);
  1626. $.extend(Uploader.options, {
  1627. /**
  1628. * @property {Object} [thumb]
  1629. * @namespace options
  1630. * @for Uploader
  1631. * @description 配置生成缩略图的选项。
  1632. *
  1633. * 默认为:
  1634. *
  1635. * ```javascript
  1636. * {
  1637. * width: 110,
  1638. * height: 110,
  1639. *
  1640. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1641. * quality: 70,
  1642. *
  1643. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1644. * allowMagnify: true,
  1645. *
  1646. * // 是否允许裁剪。
  1647. * crop: true,
  1648. *
  1649. * // 是否保留头部meta信息。
  1650. * preserveHeaders: false,
  1651. *
  1652. * // 为空的话则保留原有图片格式。
  1653. * // 否则强制转换成指定的类型。
  1654. * type: 'image/jpeg'
  1655. * }
  1656. * ```
  1657. */
  1658. thumb: {
  1659. width: 110,
  1660. height: 110,
  1661. quality: 70,
  1662. allowMagnify: true,
  1663. crop: true,
  1664. preserveHeaders: false,
  1665. // 为空的话则保留原有图片格式。
  1666. // 否则强制转换成指定的类型。
  1667. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1668. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1669. type: 'image/jpeg'
  1670. },
  1671. /**
  1672. * @property {Object} [compress]
  1673. * @namespace options
  1674. * @for Uploader
  1675. * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
  1676. *
  1677. * 默认为:
  1678. *
  1679. * ```javascript
  1680. * {
  1681. * width: 1600,
  1682. * height: 1600,
  1683. *
  1684. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1685. * quality: 90,
  1686. *
  1687. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1688. * allowMagnify: false,
  1689. *
  1690. * // 是否允许裁剪。
  1691. * crop: false,
  1692. *
  1693. * // 是否保留头部meta信息。
  1694. * preserveHeaders: true
  1695. * }
  1696. * ```
  1697. */
  1698. compress: {
  1699. width: 1600,
  1700. height: 1600,
  1701. quality: 90,
  1702. allowMagnify: false,
  1703. crop: false,
  1704. preserveHeaders: true
  1705. }
  1706. });
  1707. return Uploader.register({
  1708. 'make-thumb': 'makeThumb',
  1709. 'before-send-file': 'compressImage'
  1710. }, {
  1711. /**
  1712. * 生成缩略图,此过程为异步,所以需要传入`callback`。
  1713. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
  1714. *
  1715. * `callback`中可以接收到两个参数。
  1716. * * 第一个为error,如果生成缩略图有错误,此error将为真。
  1717. * * 第二个为ret, 缩略图的Data URL值。
  1718. *
  1719. * **注意**
  1720. * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
  1721. *
  1722. *
  1723. * @method makeThumb
  1724. * @grammar makeThumb( file, callback ) => undefined
  1725. * @grammar makeThumb( file, callback, width, height ) => undefined
  1726. * @for Uploader
  1727. * @example
  1728. *
  1729. * uploader.on( 'fileQueued', function( file ) {
  1730. * var $li = ...;
  1731. *
  1732. * uploader.makeThumb( file, function( error, ret ) {
  1733. * if ( error ) {
  1734. * $li.text('预览错误');
  1735. * } else {
  1736. * $li.append('<img alt="" src="' + ret + '" />');
  1737. * }
  1738. * });
  1739. *
  1740. * });
  1741. */
  1742. makeThumb: function (file, cb, width, height) {
  1743. var opts, image;
  1744. file = this.request('get-file', file);
  1745. // 只预览图片格式。
  1746. if (!file.type.match(/^image/)) {
  1747. cb(true);
  1748. return;
  1749. }
  1750. opts = $.extend({}, this.options.thumb);
  1751. // 如果传入的是object.
  1752. if ($.isPlainObject(width)) {
  1753. opts = $.extend(opts, width);
  1754. width = null;
  1755. }
  1756. width = width || opts.width;
  1757. height = height || opts.height;
  1758. image = new Image(opts);
  1759. image.once('load', function () {
  1760. file._info = file._info || image.info();
  1761. file._meta = file._meta || image.meta();
  1762. image.resize(width, height);
  1763. });
  1764. image.once('complete', function () {
  1765. cb(false, image.getAsDataUrl(opts.type));
  1766. image.destroy();
  1767. });
  1768. image.once('error', function () {
  1769. cb(true);
  1770. image.destroy();
  1771. });
  1772. throttle(image, file.source.size, function () {
  1773. file._info && image.info(file._info);
  1774. file._meta && image.meta(file._meta);
  1775. image.loadFromBlob(file.source);
  1776. });
  1777. },
  1778. compressImage: function (file) {
  1779. var opts = this.options.compress || this.options.resize,
  1780. compressSize = opts && opts.compressSize || 300 * 1024,
  1781. image, deferred;
  1782. file = this.request('get-file', file);
  1783. // 只预览图片格式。
  1784. if (!opts || !~'image/jpeg,image/jpg'.indexOf(file.type) ||
  1785. file.size < compressSize ||
  1786. file._compressed) {
  1787. return;
  1788. }
  1789. opts = $.extend({}, opts);
  1790. deferred = Base.Deferred();
  1791. image = new Image(opts);
  1792. deferred.always(function () {
  1793. image.destroy();
  1794. image = null;
  1795. });
  1796. image.once('error', deferred.reject);
  1797. image.once('load', function () {
  1798. file._info = file._info || image.info();
  1799. file._meta = file._meta || image.meta();
  1800. image.resize(opts.width, opts.height);
  1801. });
  1802. image.once('complete', function () {
  1803. var blob, size;
  1804. // 移动端 UC / qq 浏览器的无图模式下
  1805. // ctx.getImageData 处理大图的时候会报 Exception
  1806. // INDEX_SIZE_ERR: DOM Exception 1
  1807. try {
  1808. blob = image.getAsBlob(opts.type);
  1809. size = file.size;
  1810. // 如果压缩后,比原来还大则不用压缩后的。
  1811. if (blob.size < size) {
  1812. // file.source.destroy && file.source.destroy();
  1813. file.source = blob;
  1814. file.size = blob.size;
  1815. file.trigger('resize', blob.size, size);
  1816. }
  1817. // 标记,避免重复压缩。
  1818. file._compressed = true;
  1819. deferred.resolve();
  1820. } catch (e) {
  1821. // 出错了直接继续,让其上传原始图片
  1822. deferred.resolve();
  1823. }
  1824. });
  1825. file._info && image.info(file._info);
  1826. file._meta && image.meta(file._meta);
  1827. image.loadFromBlob(file.source);
  1828. return deferred.promise();
  1829. }
  1830. });
  1831. });
  1832. /**
  1833. * @fileOverview 文件属性封装
  1834. */
  1835. define('file', [
  1836. 'base',
  1837. 'mediator'
  1838. ], function (Base, Mediator) {
  1839. var $ = Base.$,
  1840. idPrefix = 'WU_FILE_',
  1841. idSuffix = 0,
  1842. rExt = /\.([^.]+)$/,
  1843. statusMap = {};
  1844. function gid() {
  1845. return idPrefix + idSuffix++;
  1846. }
  1847. /**
  1848. * 文件类
  1849. * @class File
  1850. * @constructor 构造函数
  1851. * @grammar new File( source ) => File
  1852. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。
  1853. */
  1854. function WUFile(source) {
  1855. /**
  1856. * 文件名,包括扩展名(后缀)
  1857. * @property name
  1858. * @type {string}
  1859. */
  1860. this.name = source.name || 'Untitled';
  1861. /**
  1862. * 文件体积(字节)
  1863. * @property size
  1864. * @type {uint}
  1865. * @default 0
  1866. */
  1867. this.size = source.size || 0;
  1868. /**
  1869. * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1870. * @property type
  1871. * @type {string}
  1872. * @default 'application'
  1873. */
  1874. this.type = source.type || 'application';
  1875. /**
  1876. * 文件最后修改日期
  1877. * @property lastModifiedDate
  1878. * @type {int}
  1879. * @default 当前时间戳
  1880. */
  1881. this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
  1882. /**
  1883. * 文件ID,每个对象具有唯一ID,与文件名无关
  1884. * @property id
  1885. * @type {string}
  1886. */
  1887. this.id = gid();
  1888. /**
  1889. * 文件扩展名,通过文件名获取,例如test.png的扩展名为png
  1890. * @property ext
  1891. * @type {string}
  1892. */
  1893. this.ext = rExt.exec(this.name) ? RegExp.$1 : '';
  1894. /**
  1895. * 状态文字说明。在不同的status语境下有不同的用途。
  1896. * @property statusText
  1897. * @type {string}
  1898. */
  1899. this.statusText = '';
  1900. // 存储文件状态,防止通过属性直接修改
  1901. statusMap[this.id] = WUFile.Status.INITED;
  1902. this.source = source;
  1903. this.loaded = 0;
  1904. this.on('error', function (msg) {
  1905. this.setStatus(WUFile.Status.ERROR, msg);
  1906. });
  1907. }
  1908. $.extend(WUFile.prototype, {
  1909. /**
  1910. * 设置状态,状态变化时会触发`change`事件。
  1911. * @method setStatus
  1912. * @grammar setStatus( status[, statusText] );
  1913. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1914. * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
  1915. */
  1916. setStatus: function (status, text) {
  1917. var prevStatus = statusMap[this.id];
  1918. typeof text !== 'undefined' && (this.statusText = text);
  1919. if (status !== prevStatus) {
  1920. statusMap[this.id] = status;
  1921. /**
  1922. * 文件状态变化
  1923. * @event statuschange
  1924. */
  1925. this.trigger('statuschange', status, prevStatus);
  1926. }
  1927. },
  1928. /**
  1929. * 获取文件状态
  1930. * @return {File.Status}
  1931. * @example
  1932. 文件状态具体包括以下几种类型:
  1933. {
  1934. // 初始化
  1935. INITED: 0,
  1936. // 已入队列
  1937. QUEUED: 1,
  1938. // 正在上传
  1939. PROGRESS: 2,
  1940. // 上传出错
  1941. ERROR: 3,
  1942. // 上传成功
  1943. COMPLETE: 4,
  1944. // 上传取消
  1945. CANCELLED: 5
  1946. }
  1947. */
  1948. getStatus: function () {
  1949. return statusMap[this.id];
  1950. },
  1951. /**
  1952. * 获取文件原始信息。
  1953. * @return {*}
  1954. */
  1955. getSource: function () {
  1956. return this.source;
  1957. },
  1958. destory: function () {
  1959. delete statusMap[this.id];
  1960. }
  1961. });
  1962. Mediator.installTo(WUFile.prototype);
  1963. /**
  1964. * 文件状态值,具体包括以下几种类型:
  1965. * * `inited` 初始状态
  1966. * * `queued` 已经进入队列, 等待上传
  1967. * * `progress` 上传中
  1968. * * `complete` 上传完成。
  1969. * * `error` 上传出错,可重试
  1970. * * `interrupt` 上传中断,可续传。
  1971. * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
  1972. * * `cancelled` 文件被移除。
  1973. * @property {Object} Status
  1974. * @namespace File
  1975. * @class File
  1976. * @static
  1977. */
  1978. WUFile.Status = {
  1979. INITED: 'inited', // 初始状态
  1980. QUEUED: 'queued', // 已经进入队列, 等待上传
  1981. PROGRESS: 'progress', // 上传中
  1982. ERROR: 'error', // 上传出错,可重试
  1983. COMPLETE: 'complete', // 上传完成。
  1984. CANCELLED: 'cancelled', // 上传取消。
  1985. INTERRUPT: 'interrupt', // 上传中断,可续传。
  1986. INVALID: 'invalid' // 文件不合格,不能重试上传。
  1987. };
  1988. return WUFile;
  1989. });
  1990. /**
  1991. * @fileOverview 文件队列
  1992. */
  1993. define('queue', [
  1994. 'base',
  1995. 'mediator',
  1996. 'file'
  1997. ], function (Base, Mediator, WUFile) {
  1998. var $ = Base.$,
  1999. STATUS = WUFile.Status;
  2000. /**
  2001. * 文件队列, 用来存储各个状态中的文件。
  2002. * @class Queue
  2003. * @extends Mediator
  2004. */
  2005. function Queue() {
  2006. /**
  2007. * 统计文件数。
  2008. * * `numOfQueue` 队列中的文件数。
  2009. * * `numOfSuccess` 上传成功的文件数
  2010. * * `numOfCancel` 被移除的文件数
  2011. * * `numOfProgress` 正在上传中的文件数
  2012. * * `numOfUploadFailed` 上传错误的文件数。
  2013. * * `numOfInvalid` 无效的文件数。
  2014. * @property {Object} stats
  2015. */
  2016. this.stats = {
  2017. numOfQueue: 0,
  2018. numOfSuccess: 0,
  2019. numOfCancel: 0,
  2020. numOfProgress: 0,
  2021. numOfUploadFailed: 0,
  2022. numOfInvalid: 0
  2023. };
  2024. // 上传队列,仅包括等待上传的文件
  2025. this._queue = [];
  2026. // 存储所有文件
  2027. this._map = {};
  2028. }
  2029. $.extend(Queue.prototype, {
  2030. /**
  2031. * 将新文件加入对队列尾部
  2032. *
  2033. * @method append
  2034. * @param {File} file 文件对象
  2035. */
  2036. append: function (file) {
  2037. this._queue.push(file);
  2038. this._fileAdded(file);
  2039. return this;
  2040. },
  2041. /**
  2042. * 将新文件加入对队列头部
  2043. *
  2044. * @method prepend
  2045. * @param {File} file 文件对象
  2046. */
  2047. prepend: function (file) {
  2048. this._queue.unshift(file);
  2049. this._fileAdded(file);
  2050. return this;
  2051. },
  2052. /**
  2053. * 获取文件对象
  2054. *
  2055. * @method getFile
  2056. * @param {String} fileId 文件ID
  2057. * @return {File}
  2058. */
  2059. getFile: function (fileId) {
  2060. if (typeof fileId !== 'string') {
  2061. return fileId;
  2062. }
  2063. return this._map[fileId];
  2064. },
  2065. /**
  2066. * 从队列中取出一个指定状态的文件。
  2067. * @grammar fetch( status ) => File
  2068. * @method fetch
  2069. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  2070. * @return {File} [File](#WebUploader:File)
  2071. */
  2072. fetch: function (status) {
  2073. var len = this._queue.length,
  2074. i, file;
  2075. status = status || STATUS.QUEUED;
  2076. for (i = 0; i < len; i++) {
  2077. file = this._queue[i];
  2078. if (status === file.getStatus()) {
  2079. return file;
  2080. }
  2081. }
  2082. return null;
  2083. },
  2084. /**
  2085. * 对队列进行排序,能够控制文件上传顺序。
  2086. * @grammar sort( fn ) => undefined
  2087. * @method sort
  2088. * @param {Function} fn 排序方法
  2089. */
  2090. sort: function (fn) {
  2091. if (typeof fn === 'function') {
  2092. this._queue.sort(fn);
  2093. }
  2094. },
  2095. /**
  2096. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。
  2097. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  2098. * @method getFiles
  2099. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  2100. */
  2101. getFiles: function () {
  2102. var sts = [].slice.call(arguments, 0),
  2103. ret = [],
  2104. i = 0,
  2105. len = this._queue.length,
  2106. file;
  2107. for (; i < len; i++) {
  2108. file = this._queue[i];
  2109. if (sts.length && !~$.inArray(file.getStatus(), sts)) {
  2110. continue;
  2111. }
  2112. ret.push(file);
  2113. }
  2114. return ret;
  2115. },
  2116. _fileAdded: function (file) {
  2117. var me = this,
  2118. existing = this._map[file.id];
  2119. if (!existing) {
  2120. this._map[file.id] = file;
  2121. file.on('statuschange', function (cur, pre) {
  2122. me._onFileStatusChange(cur, pre);
  2123. });
  2124. }
  2125. file.setStatus(STATUS.QUEUED);
  2126. },
  2127. _onFileStatusChange: function (curStatus, preStatus) {
  2128. var stats = this.stats;
  2129. switch (preStatus) {
  2130. case STATUS.PROGRESS:
  2131. stats.numOfProgress--;
  2132. break;
  2133. case STATUS.QUEUED:
  2134. stats.numOfQueue--;
  2135. break;
  2136. case STATUS.ERROR:
  2137. stats.numOfUploadFailed--;
  2138. break;
  2139. case STATUS.INVALID:
  2140. stats.numOfInvalid--;
  2141. break;
  2142. }
  2143. switch (curStatus) {
  2144. case STATUS.QUEUED:
  2145. stats.numOfQueue++;
  2146. break;
  2147. case STATUS.PROGRESS:
  2148. stats.numOfProgress++;
  2149. break;
  2150. case STATUS.ERROR:
  2151. stats.numOfUploadFailed++;
  2152. break;
  2153. case STATUS.COMPLETE:
  2154. stats.numOfSuccess++;
  2155. break;
  2156. case STATUS.CANCELLED:
  2157. stats.numOfCancel++;
  2158. break;
  2159. case STATUS.INVALID:
  2160. stats.numOfInvalid++;
  2161. break;
  2162. }
  2163. }
  2164. });
  2165. Mediator.installTo(Queue.prototype);
  2166. return Queue;
  2167. });
  2168. /**
  2169. * @fileOverview 队列
  2170. */
  2171. define('widgets/queue', [
  2172. 'base',
  2173. 'uploader',
  2174. 'queue',
  2175. 'file',
  2176. 'lib/file',
  2177. 'runtime/client',
  2178. 'widgets/widget'
  2179. ], function (Base, Uploader, Queue, WUFile, File, RuntimeClient) {
  2180. var $ = Base.$,
  2181. rExt = /\.\w+$/,
  2182. Status = WUFile.Status;
  2183. return Uploader.register({
  2184. 'sort-files': 'sortFiles',
  2185. 'add-file': 'addFiles',
  2186. 'get-file': 'getFile',
  2187. 'fetch-file': 'fetchFile',
  2188. 'get-stats': 'getStats',
  2189. 'get-files': 'getFiles',
  2190. 'remove-file': 'removeFile',
  2191. 'retry': 'retry',
  2192. 'reset': 'reset',
  2193. 'accept-file': 'acceptFile'
  2194. }, {
  2195. init: function (opts) {
  2196. var me = this,
  2197. deferred, len, i, item, arr, accept, runtime;
  2198. if ($.isPlainObject(opts.accept)) {
  2199. opts.accept = [opts.accept];
  2200. }
  2201. // accept中的中生成匹配正则。
  2202. if (opts.accept) {
  2203. arr = [];
  2204. for (i = 0, len = opts.accept.length; i < len; i++) {
  2205. item = opts.accept[i].extensions;
  2206. item && arr.push(item);
  2207. }
  2208. if (arr.length) {
  2209. accept = '\\.' + arr.join(',')
  2210. .replace(/,/g, '$|\\.')
  2211. .replace(/\*/g, '.*') + '$';
  2212. }
  2213. me.accept = new RegExp(accept, 'i');
  2214. }
  2215. me.queue = new Queue();
  2216. me.stats = me.queue.stats;
  2217. // 如果当前不是html5运行时,那就算了。
  2218. // 不执行后续操作
  2219. if (this.request('predict-runtime-type') !== 'html5') {
  2220. return;
  2221. }
  2222. // 创建一个 html5 运行时的 placeholder
  2223. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2224. deferred = Base.Deferred();
  2225. runtime = new RuntimeClient('Placeholder');
  2226. runtime.connectRuntime({
  2227. runtimeOrder: 'html5'
  2228. }, function () {
  2229. me._ruid = runtime.getRuid();
  2230. deferred.resolve();
  2231. });
  2232. return deferred.promise();
  2233. },
  2234. // 为了支持外部直接添加一个原生File对象。
  2235. _wrapFile: function (file) {
  2236. if (!(file instanceof WUFile)) {
  2237. if (!(file instanceof File)) {
  2238. if (!this._ruid) {
  2239. throw new Error('Can\'t add external files.');
  2240. }
  2241. file = new File(this._ruid, file);
  2242. }
  2243. file = new WUFile(file);
  2244. }
  2245. return file;
  2246. },
  2247. // 判断文件是否可以被加入队列
  2248. acceptFile: function (file) {
  2249. var invalid = !file || file.size < 6 || this.accept &&
  2250. // 如果名字中有后缀,才做后缀白名单处理。
  2251. rExt.exec(file.name) && !this.accept.test(file.name);
  2252. return !invalid;
  2253. },
  2254. /**
  2255. * @event beforeFileQueued
  2256. * @param {File} file File对象
  2257. * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
  2258. * @for Uploader
  2259. */
  2260. /**
  2261. * @event fileQueued
  2262. * @param {File} file File对象
  2263. * @description 当文件被加入队列以后触发。
  2264. * @for Uploader
  2265. */
  2266. _addFile: function (file) {
  2267. var me = this;
  2268. file = me._wrapFile(file);
  2269. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2270. if (!me.owner.trigger('beforeFileQueued', file)) {
  2271. return;
  2272. }
  2273. // 类型不匹配,则派送错误事件,并返回。
  2274. if (!me.acceptFile(file)) {
  2275. me.owner.trigger('error', 'Q_TYPE_DENIED', file);
  2276. return;
  2277. }
  2278. me.queue.append(file);
  2279. me.owner.trigger('fileQueued', file);
  2280. return file;
  2281. },
  2282. getFile: function (fileId) {
  2283. return this.queue.getFile(fileId);
  2284. },
  2285. /**
  2286. * @event filesQueued
  2287. * @param {File} files 数组,内容为原始File(lib/File)对象。
  2288. * @description 当一批文件添加进队列以后触发。
  2289. * @for Uploader
  2290. */
  2291. /**
  2292. * @method addFiles
  2293. * @grammar addFiles( file ) => undefined
  2294. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2295. * @param {Array of File or File} [files] Files 对象 数组
  2296. * @description 添加文件到队列
  2297. * @for Uploader
  2298. */
  2299. addFiles: function (files) {
  2300. var me = this;
  2301. if (!files.length) {
  2302. files = [files];
  2303. }
  2304. files = $.map(files, function (file) {
  2305. return me._addFile(file);
  2306. });
  2307. me.owner.trigger('filesQueued', files);
  2308. if (me.options.auto) {
  2309. me.request('start-upload');
  2310. }
  2311. },
  2312. getStats: function () {
  2313. return this.stats;
  2314. },
  2315. /**
  2316. * @event fileDequeued
  2317. * @param {File} file File对象
  2318. * @description 当文件被移除队列后触发。
  2319. * @for Uploader
  2320. */
  2321. /**
  2322. * @method removeFile
  2323. * @grammar removeFile( file ) => undefined
  2324. * @grammar removeFile( id ) => undefined
  2325. * @param {File|id} file File对象或这File对象的id
  2326. * @description 移除某一文件。
  2327. * @for Uploader
  2328. * @example
  2329. *
  2330. * $li.on('click', '.remove-this', function() {
  2331. * uploader.removeFile( file );
  2332. * })
  2333. */
  2334. removeFile: function (file) {
  2335. var me = this;
  2336. file = file.id ? file : me.queue.getFile(file);
  2337. file.setStatus(Status.CANCELLED);
  2338. me.owner.trigger('fileDequeued', file);
  2339. },
  2340. /**
  2341. * @method getFiles
  2342. * @grammar getFiles() => Array
  2343. * @grammar getFiles( status1, status2, status... ) => Array
  2344. * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
  2345. * @for Uploader
  2346. * @example
  2347. * console.log( uploader.getFiles() ); // => all files
  2348. * console.log( uploader.getFiles('error') ) // => all error files.
  2349. */
  2350. getFiles: function () {
  2351. return this.queue.getFiles.apply(this.queue, arguments);
  2352. },
  2353. fetchFile: function () {
  2354. return this.queue.fetch.apply(this.queue, arguments);
  2355. },
  2356. /**
  2357. * @method retry
  2358. * @grammar retry() => undefined
  2359. * @grammar retry( file ) => undefined
  2360. * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
  2361. * @for Uploader
  2362. * @example
  2363. * function retry() {
  2364. * uploader.retry();
  2365. * }
  2366. */
  2367. retry: function (file, noForceStart) {
  2368. var me = this,
  2369. files, i, len;
  2370. if (file) {
  2371. file = file.id ? file : me.queue.getFile(file);
  2372. file.setStatus(Status.QUEUED);
  2373. noForceStart || me.request('start-upload');
  2374. return;
  2375. }
  2376. files = me.queue.getFiles(Status.ERROR);
  2377. i = 0;
  2378. len = files.length;
  2379. for (; i < len; i++) {
  2380. file = files[i];
  2381. file.setStatus(Status.QUEUED);
  2382. }
  2383. me.request('start-upload');
  2384. },
  2385. /**
  2386. * @method sort
  2387. * @grammar sort( fn ) => undefined
  2388. * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
  2389. * @for Uploader
  2390. */
  2391. sortFiles: function () {
  2392. return this.queue.sort.apply(this.queue, arguments);
  2393. },
  2394. /**
  2395. * @method reset
  2396. * @grammar reset() => undefined
  2397. * @description 重置uploader。目前只重置了队列。
  2398. * @for Uploader
  2399. * @example
  2400. * uploader.reset();
  2401. */
  2402. reset: function () {
  2403. this.queue = new Queue();
  2404. this.stats = this.queue.stats;
  2405. }
  2406. });
  2407. });
  2408. /**
  2409. * @fileOverview 添加获取Runtime相关信息的方法。
  2410. */
  2411. define('widgets/runtime', [
  2412. 'uploader',
  2413. 'runtime/runtime',
  2414. 'widgets/widget'
  2415. ], function (Uploader, Runtime) {
  2416. Uploader.support = function () {
  2417. return Runtime.hasRuntime.apply(Runtime, arguments);
  2418. };
  2419. return Uploader.register({
  2420. 'predict-runtime-type': 'predictRuntmeType'
  2421. }, {
  2422. init: function () {
  2423. if (!this.predictRuntmeType()) {
  2424. throw Error('Runtime Error');
  2425. }
  2426. },
  2427. /**
  2428. * 预测Uploader将采用哪个`Runtime`
  2429. * @grammar predictRuntmeType() => String
  2430. * @method predictRuntmeType
  2431. * @for Uploader
  2432. */
  2433. predictRuntmeType: function () {
  2434. var orders = this.options.runtimeOrder || Runtime.orders,
  2435. type = this.type,
  2436. i, len;
  2437. if (!type) {
  2438. orders = orders.split(/\s*,\s*/g);
  2439. for (i = 0, len = orders.length; i < len; i++) {
  2440. if (Runtime.hasRuntime(orders[i])) {
  2441. this.type = type = orders[i];
  2442. break;
  2443. }
  2444. }
  2445. }
  2446. return type;
  2447. }
  2448. });
  2449. });
  2450. /**
  2451. * @fileOverview Transport
  2452. */
  2453. define('lib/transport', [
  2454. 'base',
  2455. 'runtime/client',
  2456. 'mediator'
  2457. ], function (Base, RuntimeClient, Mediator) {
  2458. var $ = Base.$;
  2459. function Transport(opts) {
  2460. var me = this;
  2461. opts = me.options = $.extend(true, {}, Transport.options, opts || {});
  2462. RuntimeClient.call(this, 'Transport');
  2463. this._blob = null;
  2464. this._formData = opts.formData || {};
  2465. this._headers = opts.headers || {};
  2466. this.on('progress', this._timeout);
  2467. this.on('load error', function () {
  2468. me.trigger('progress', 1);
  2469. clearTimeout(me._timer);
  2470. });
  2471. }
  2472. Transport.options = {
  2473. server: '',
  2474. method: 'POST',
  2475. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2476. withCredentials: false,
  2477. fileVal: 'file',
  2478. timeout: 2 * 60 * 1000, // 2分钟
  2479. formData: {},
  2480. headers: {},
  2481. sendAsBinary: false
  2482. };
  2483. $.extend(Transport.prototype, {
  2484. // 添加Blob, 只能添加一次,最后一次有效。
  2485. appendBlob: function (key, blob, filename) {
  2486. var me = this,
  2487. opts = me.options;
  2488. if (me.getRuid()) {
  2489. me.disconnectRuntime();
  2490. }
  2491. // 连接到blob归属的同一个runtime.
  2492. me.connectRuntime(blob.ruid, function () {
  2493. me.exec('init');
  2494. });
  2495. me._blob = blob;
  2496. opts.fileVal = key || opts.fileVal;
  2497. opts.filename = filename || opts.filename;
  2498. },
  2499. // 添加其他字段
  2500. append: function (key, value) {
  2501. if (typeof key === 'object') {
  2502. $.extend(this._formData, key);
  2503. } else {
  2504. this._formData[key] = value;
  2505. }
  2506. },
  2507. setRequestHeader: function (key, value) {
  2508. if (typeof key === 'object') {
  2509. $.extend(this._headers, key);
  2510. } else {
  2511. this._headers[key] = value;
  2512. }
  2513. },
  2514. send: function (method) {
  2515. this.exec('send', method);
  2516. this._timeout();
  2517. },
  2518. abort: function () {
  2519. clearTimeout(this._timer);
  2520. return this.exec('abort');
  2521. },
  2522. destroy: function () {
  2523. this.trigger('destroy');
  2524. this.off();
  2525. this.exec('destroy');
  2526. this.disconnectRuntime();
  2527. },
  2528. getResponse: function () {
  2529. return this.exec('getResponse');
  2530. },
  2531. getResponseAsJson: function () {
  2532. return this.exec('getResponseAsJson');
  2533. },
  2534. getStatus: function () {
  2535. return this.exec('getStatus');
  2536. },
  2537. _timeout: function () {
  2538. var me = this,
  2539. duration = me.options.timeout;
  2540. if (!duration) {
  2541. return;
  2542. }
  2543. clearTimeout(me._timer);
  2544. me._timer = setTimeout(function () {
  2545. me.abort();
  2546. me.trigger('error', 'timeout');
  2547. }, duration);
  2548. }
  2549. });
  2550. // 让Transport具备事件功能。
  2551. Mediator.installTo(Transport.prototype);
  2552. return Transport;
  2553. });
  2554. /**
  2555. * @fileOverview 负责文件上传相关。
  2556. */
  2557. define('widgets/upload', [
  2558. 'base',
  2559. 'uploader',
  2560. 'file',
  2561. 'lib/transport',
  2562. 'widgets/widget'
  2563. ], function (Base, Uploader, WUFile, Transport) {
  2564. var $ = Base.$,
  2565. isPromise = Base.isPromise,
  2566. Status = WUFile.Status;
  2567. // 添加默认配置项
  2568. $.extend(Uploader.options, {
  2569. /**
  2570. * @property {Boolean} [prepareNextFile=false]
  2571. * @namespace options
  2572. * @for Uploader
  2573. * @description 是否允许在文件传输时提前把下一个文件准备好。
  2574. * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
  2575. * 如果能提前在当前文件传输期处理,可以节省总体耗时。
  2576. */
  2577. prepareNextFile: false,
  2578. /**
  2579. * @property {Boolean} [chunked=false]
  2580. * @namespace options
  2581. * @for Uploader
  2582. * @description 是否要分片处理大文件上传。
  2583. */
  2584. chunked: false,
  2585. /**
  2586. * @property {Boolean} [chunkSize=5242880]
  2587. * @namespace options
  2588. * @for Uploader
  2589. * @description 如果要分片,分多大一片? 默认大小为5M.
  2590. */
  2591. chunkSize: 5 * 1024 * 1024,
  2592. /**
  2593. * @property {Boolean} [chunkRetry=2]
  2594. * @namespace options
  2595. * @for Uploader
  2596. * @description 如果某个分片由于网络问题出错,允许自动重传多少次?
  2597. */
  2598. chunkRetry: 2,
  2599. /**
  2600. * @property {Boolean} [threads=3]
  2601. * @namespace options
  2602. * @for Uploader
  2603. * @description 上传并发数。允许同时最大上传进程数。
  2604. */
  2605. threads: 3,
  2606. /**
  2607. * @property {Object} [formData]
  2608. * @namespace options
  2609. * @for Uploader
  2610. * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
  2611. */
  2612. formData: null
  2613. /**
  2614. * @property {Object} [fileVal='file']
  2615. * @namespace options
  2616. * @for Uploader
  2617. * @description 设置文件上传域的name。
  2618. */
  2619. /**
  2620. * @property {Object} [method='POST']
  2621. * @namespace options
  2622. * @for Uploader
  2623. * @description 文件上传方式,`POST`或者`GET`。
  2624. */
  2625. /**
  2626. * @property {Object} [sendAsBinary=false]
  2627. * @namespace options
  2628. * @for Uploader
  2629. * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
  2630. * 其他参数在$_GET数组中。
  2631. */
  2632. });
  2633. // 负责将文件切片。
  2634. function CuteFile(file, chunkSize) {
  2635. var pending = [],
  2636. blob = file.source,
  2637. total = blob.size,
  2638. chunks = chunkSize ? Math.ceil(total / chunkSize) : 1,
  2639. start = 0,
  2640. index = 0,
  2641. len;
  2642. while (index < chunks) {
  2643. len = Math.min(chunkSize, total - start);
  2644. pending.push({
  2645. file: file,
  2646. start: start,
  2647. end: chunkSize ? (start + len) : total,
  2648. total: total,
  2649. chunks: chunks,
  2650. chunk: index++
  2651. });
  2652. start += len;
  2653. }
  2654. file.blocks = pending.concat();
  2655. file.remaning = pending.length;
  2656. return {
  2657. file: file,
  2658. has: function () {
  2659. return !!pending.length;
  2660. },
  2661. fetch: function () {
  2662. return pending.shift();
  2663. }
  2664. };
  2665. }
  2666. Uploader.register({
  2667. 'start-upload': 'start',
  2668. 'stop-upload': 'stop',
  2669. 'skip-file': 'skipFile',
  2670. 'is-in-progress': 'isInProgress'
  2671. }, {
  2672. init: function () {
  2673. var owner = this.owner;
  2674. this.runing = false;
  2675. // 记录当前正在传的数据,跟threads相关
  2676. this.pool = [];
  2677. // 缓存即将上传的文件。
  2678. this.pending = [];
  2679. // 跟踪还有多少分片没有完成上传。
  2680. this.remaning = 0;
  2681. this.__tick = Base.bindFn(this._tick, this);
  2682. owner.on('uploadComplete', function (file) {
  2683. // 把其他块取消了。
  2684. file.blocks && $.each(file.blocks, function (_, v) {
  2685. v.transport && (v.transport.abort(), v.transport.destroy());
  2686. delete v.transport;
  2687. });
  2688. delete file.blocks;
  2689. delete file.remaning;
  2690. });
  2691. },
  2692. /**
  2693. * @event startUpload
  2694. * @description 当开始上传流程时触发。
  2695. * @for Uploader
  2696. */
  2697. /**
  2698. * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  2699. * @grammar upload() => undefined
  2700. * @method upload
  2701. * @for Uploader
  2702. */
  2703. start: function () {
  2704. var me = this;
  2705. // 移出invalid的文件
  2706. $.each(me.request('get-files', Status.INVALID), function () {
  2707. me.request('remove-file', this);
  2708. });
  2709. if (me.runing) {
  2710. return;
  2711. }
  2712. me.runing = true;
  2713. // 如果有暂停的,则续传
  2714. $.each(me.pool, function (_, v) {
  2715. var file = v.file;
  2716. if (file.getStatus() === Status.INTERRUPT) {
  2717. file.setStatus(Status.PROGRESS);
  2718. me._trigged = false;
  2719. v.transport && v.transport.send();
  2720. }
  2721. });
  2722. me._trigged = false;
  2723. me.owner.trigger('startUpload');
  2724. Base.nextTick(me.__tick);
  2725. },
  2726. /**
  2727. * @event stopUpload
  2728. * @description 当开始上传流程暂停时触发。
  2729. * @for Uploader
  2730. */
  2731. /**
  2732. * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
  2733. * @grammar stop() => undefined
  2734. * @grammar stop( true ) => undefined
  2735. * @method stop
  2736. * @for Uploader
  2737. */
  2738. stop: function (interrupt) {
  2739. var me = this;
  2740. if (me.runing === false) {
  2741. return;
  2742. }
  2743. me.runing = false;
  2744. interrupt && $.each(me.pool, function (_, v) {
  2745. v.transport && v.transport.abort();
  2746. v.file.setStatus(Status.INTERRUPT);
  2747. });
  2748. me.owner.trigger('stopUpload');
  2749. },
  2750. /**
  2751. * 判断`Uplaode`r是否正在上传中。
  2752. * @grammar isInProgress() => Boolean
  2753. * @method isInProgress
  2754. * @for Uploader
  2755. */
  2756. isInProgress: function () {
  2757. return !!this.runing;
  2758. },
  2759. getStats: function () {
  2760. return this.request('get-stats');
  2761. },
  2762. /**
  2763. * 掉过一个文件上传,直接标记指定文件为已上传状态。
  2764. * @grammar skipFile( file ) => undefined
  2765. * @method skipFile
  2766. * @for Uploader
  2767. */
  2768. skipFile: function (file, status) {
  2769. file = this.request('get-file', file);
  2770. file.setStatus(status || Status.COMPLETE);
  2771. file.skipped = true;
  2772. // 如果正在上传。
  2773. file.blocks && $.each(file.blocks, function (_, v) {
  2774. var _tr = v.transport;
  2775. if (_tr) {
  2776. _tr.abort();
  2777. _tr.destroy();
  2778. delete v.transport;
  2779. }
  2780. });
  2781. this.owner.trigger('uploadSkip', file);
  2782. },
  2783. /**
  2784. * @event uploadFinished
  2785. * @description 当所有文件上传结束时触发。
  2786. * @for Uploader
  2787. */
  2788. _tick: function () {
  2789. var me = this,
  2790. opts = me.options,
  2791. fn, val;
  2792. // 上一个promise还没有结束,则等待完成后再执行。
  2793. if (me._promise) {
  2794. return me._promise.always(me.__tick);
  2795. }
  2796. // 还有位置,且还有文件要处理的话。
  2797. if (me.pool.length < opts.threads && (val = me._nextBlock())) {
  2798. me._trigged = false;
  2799. fn = function (val) {
  2800. me._promise = null;
  2801. // 有可能是reject过来的,所以要检测val的类型。
  2802. val && val.file && me._startSend(val);
  2803. Base.nextTick(me.__tick);
  2804. };
  2805. me._promise = isPromise(val) ? val.always(fn) : fn(val);
  2806. // 没有要上传的了,且没有正在传输的了。
  2807. } else if (!me.remaning && !me.getStats().numOfQueue) {
  2808. me.runing = false;
  2809. me._trigged || Base.nextTick(function () {
  2810. me.owner.trigger('uploadFinished');
  2811. });
  2812. me._trigged = true;
  2813. }
  2814. },
  2815. _nextBlock: function () {
  2816. var me = this,
  2817. act = me._act,
  2818. opts = me.options,
  2819. next, done;
  2820. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2821. if (act && act.has() &&
  2822. act.file.getStatus() === Status.PROGRESS) {
  2823. // 是否提前准备下一个文件
  2824. if (opts.prepareNextFile && !me.pending.length) {
  2825. me._prepareNextFile();
  2826. }
  2827. return act.fetch();
  2828. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2829. } else if (me.runing) {
  2830. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2831. if (!me.pending.length && me.getStats().numOfQueue) {
  2832. me._prepareNextFile();
  2833. }
  2834. next = me.pending.shift();
  2835. done = function (file) {
  2836. if (!file) {
  2837. return null;
  2838. }
  2839. act = CuteFile(file, opts.chunked ? opts.chunkSize : 0);
  2840. me._act = act;
  2841. return act.fetch();
  2842. };
  2843. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2844. return isPromise(next) ?
  2845. next[next.pipe ? 'pipe' : 'then'](done) :
  2846. done(next);
  2847. }
  2848. },
  2849. /**
  2850. * @event uploadStart
  2851. * @param {File} file File对象
  2852. * @description 某个文件开始上传前触发,一个文件只会触发一次。
  2853. * @for Uploader
  2854. */
  2855. _prepareNextFile: function () {
  2856. var me = this,
  2857. file = me.request('fetch-file'),
  2858. pending = me.pending,
  2859. promise;
  2860. if (file) {
  2861. promise = me.request('before-send-file', file, function () {
  2862. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2863. if (file.getStatus() === Status.QUEUED) {
  2864. me.owner.trigger('uploadStart', file);
  2865. file.setStatus(Status.PROGRESS);
  2866. return file;
  2867. }
  2868. return me._finishFile(file);
  2869. });
  2870. // 如果还在pending中,则替换成文件本身。
  2871. promise.done(function () {
  2872. var idx = $.inArray(promise, pending);
  2873. ~idx && pending.splice(idx, 1, file);
  2874. });
  2875. // befeore-send-file的钩子就有错误发生。
  2876. promise.fail(function (reason) {
  2877. file.setStatus(Status.ERROR, reason);
  2878. me.owner.trigger('uploadError', file, reason);
  2879. me.owner.trigger('uploadComplete', file);
  2880. });
  2881. pending.push(promise);
  2882. }
  2883. },
  2884. // 让出位置了,可以让其他分片开始上传
  2885. _popBlock: function (block) {
  2886. var idx = $.inArray(block, this.pool);
  2887. this.pool.splice(idx, 1);
  2888. block.file.remaning--;
  2889. this.remaning--;
  2890. },
  2891. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2892. _startSend: function (block) {
  2893. var me = this,
  2894. file = block.file,
  2895. promise;
  2896. me.pool.push(block);
  2897. me.remaning++;
  2898. // 如果没有分片,则直接使用原始的。
  2899. // 不会丢失content-type信息。
  2900. block.blob = block.chunks === 1 ? file.source :
  2901. file.source.slice(block.start, block.end);
  2902. // hook, 每个分片发送之前可能要做些异步的事情。
  2903. promise = me.request('before-send', block, function () {
  2904. // 有可能文件已经上传出错了,所以不需要再传输了。
  2905. if (file.getStatus() === Status.PROGRESS) {
  2906. me._doSend(block);
  2907. } else {
  2908. me._popBlock(block);
  2909. Base.nextTick(me.__tick);
  2910. }
  2911. });
  2912. // 如果为fail了,则跳过此分片。
  2913. promise.fail(function () {
  2914. if (file.remaning === 1) {
  2915. me._finishFile(file).always(function () {
  2916. block.percentage = 1;
  2917. me._popBlock(block);
  2918. me.owner.trigger('uploadComplete', file);
  2919. Base.nextTick(me.__tick);
  2920. });
  2921. } else {
  2922. block.percentage = 1;
  2923. me._popBlock(block);
  2924. Base.nextTick(me.__tick);
  2925. }
  2926. });
  2927. },
  2928. /**
  2929. * @event uploadBeforeSend
  2930. * @param {Object} object
  2931. * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
  2932. * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
  2933. * @for Uploader
  2934. */
  2935. /**
  2936. * @event uploadAccept
  2937. * @param {Object} object
  2938. * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
  2939. * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
  2940. * @for Uploader
  2941. */
  2942. /**
  2943. * @event uploadProgress
  2944. * @param {File} file File对象
  2945. * @param {Number} percentage 上传进度
  2946. * @description 上传过程中触发,携带上传进度。
  2947. * @for Uploader
  2948. */
  2949. /**
  2950. * @event uploadError
  2951. * @param {File} file File对象
  2952. * @param {String} reason 出错的code
  2953. * @description 当文件上传出错时触发。
  2954. * @for Uploader
  2955. */
  2956. /**
  2957. * @event uploadSuccess
  2958. * @param {File} file File对象
  2959. * @param {Object} response 服务端返回的数据
  2960. * @description 当文件上传成功时触发。
  2961. * @for Uploader
  2962. */
  2963. /**
  2964. * @event uploadComplete
  2965. * @param {File} [file] File对象
  2966. * @description 不管成功或者失败,文件上传完成时触发。
  2967. * @for Uploader
  2968. */
  2969. // 做上传操作。
  2970. _doSend: function (block) {
  2971. var me = this,
  2972. owner = me.owner,
  2973. opts = me.options,
  2974. file = block.file,
  2975. tr = new Transport(opts),
  2976. data = $.extend({}, opts.formData),
  2977. headers = $.extend({}, opts.headers),
  2978. requestAccept, ret;
  2979. block.transport = tr;
  2980. tr.on('destroy', function () {
  2981. delete block.transport;
  2982. me._popBlock(block);
  2983. Base.nextTick(me.__tick);
  2984. });
  2985. // 广播上传进度。以文件为单位。
  2986. tr.on('progress', function (percentage) {
  2987. var totalPercent = 0,
  2988. uploaded = 0;
  2989. // 可能没有abort掉,progress还是执行进来了。
  2990. // if ( !file.blocks ) {
  2991. // return;
  2992. // }
  2993. totalPercent = block.percentage = percentage;
  2994. if (block.chunks > 1) { // 计算文件的整体速度。
  2995. $.each(file.blocks, function (_, v) {
  2996. uploaded += (v.percentage || 0) * (v.end - v.start);
  2997. });
  2998. totalPercent = uploaded / file.size;
  2999. }
  3000. owner.trigger('uploadProgress', file, totalPercent || 0);
  3001. });
  3002. // 用来询问,是否返回的结果是有错误的。
  3003. requestAccept = function (reject) {
  3004. var fn;
  3005. ret = tr.getResponseAsJson() || {};
  3006. ret._raw = tr.getResponse();
  3007. fn = function (value) {
  3008. reject = value;
  3009. };
  3010. // 服务端响应了,不代表成功了,询问是否响应正确。
  3011. if (!owner.trigger('uploadAccept', block, ret, fn)) {
  3012. reject = reject || 'server';
  3013. }
  3014. return reject;
  3015. };
  3016. // 尝试重试,然后广播文件上传出错。
  3017. tr.on('error', function (type, flag) {
  3018. block.retried = block.retried || 0;
  3019. // 自动重试
  3020. if (block.chunks > 1 && ~'http,abort'.indexOf(type) &&
  3021. block.retried < opts.chunkRetry) {
  3022. block.retried++;
  3023. tr.send();
  3024. } else {
  3025. // http status 500 ~ 600
  3026. if (!flag && type === 'server') {
  3027. type = requestAccept(type);
  3028. }
  3029. file.setStatus(Status.ERROR, type);
  3030. owner.trigger('uploadError', file, type);
  3031. owner.trigger('uploadComplete', file);
  3032. }
  3033. });
  3034. // 上传成功
  3035. tr.on('load', function () {
  3036. var reason;
  3037. // 如果非预期,转向上传出错。
  3038. if ((reason = requestAccept())) {
  3039. tr.trigger('error', reason, true);
  3040. return;
  3041. }
  3042. // 全部上传完成。
  3043. if (file.remaning === 1) {
  3044. me._finishFile(file, ret);
  3045. } else {
  3046. tr.destroy();
  3047. }
  3048. });
  3049. // 配置默认的上传字段。
  3050. data = $.extend(data, {
  3051. id: file.id,
  3052. name: file.name,
  3053. type: file.type,
  3054. lastModifiedDate: file.lastModifiedDate,
  3055. size: file.size
  3056. });
  3057. block.chunks > 1 && $.extend(data, {
  3058. chunks: block.chunks,
  3059. chunk: block.chunk
  3060. });
  3061. // 在发送之间可以添加字段什么的。。。
  3062. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  3063. owner.trigger('uploadBeforeSend', block, data, headers);
  3064. // 开始发送。
  3065. tr.appendBlob(opts.fileVal, block.blob, file.name);
  3066. tr.append(data);
  3067. tr.setRequestHeader(headers);
  3068. tr.send();
  3069. },
  3070. // 完成上传。
  3071. _finishFile: function (file, ret, hds) {
  3072. var owner = this.owner;
  3073. return owner
  3074. .request('after-send-file', arguments, function () {
  3075. file.setStatus(Status.COMPLETE);
  3076. owner.trigger('uploadSuccess', file, ret, hds);
  3077. })
  3078. .fail(function (reason) {
  3079. // 如果外部已经标记为invalid什么的,不再改状态。
  3080. if (file.getStatus() === Status.PROGRESS) {
  3081. file.setStatus(Status.ERROR, reason);
  3082. }
  3083. owner.trigger('uploadError', file, reason);
  3084. })
  3085. .always(function () {
  3086. owner.trigger('uploadComplete', file);
  3087. });
  3088. }
  3089. });
  3090. });
  3091. /**
  3092. * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
  3093. */
  3094. define('widgets/validator', [
  3095. 'base',
  3096. 'uploader',
  3097. 'file',
  3098. 'widgets/widget'
  3099. ], function (Base, Uploader, WUFile) {
  3100. var $ = Base.$,
  3101. validators = {},
  3102. api;
  3103. /**
  3104. * @event error
  3105. * @param {String} type 错误类型。
  3106. * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
  3107. *
  3108. * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
  3109. * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。
  3110. * @for Uploader
  3111. */
  3112. // 暴露给外面的api
  3113. api = {
  3114. // 添加验证器
  3115. addValidator: function (type, cb) {
  3116. validators[type] = cb;
  3117. },
  3118. // 移除验证器
  3119. removeValidator: function (type) {
  3120. delete validators[type];
  3121. }
  3122. };
  3123. // 在Uploader初始化的时候启动Validators的初始化
  3124. Uploader.register({
  3125. init: function () {
  3126. var me = this;
  3127. $.each(validators, function () {
  3128. this.call(me.owner);
  3129. });
  3130. }
  3131. });
  3132. /**
  3133. * @property {int} [fileNumLimit=undefined]
  3134. * @namespace options
  3135. * @for Uploader
  3136. * @description 验证文件总数量, 超出则不允许加入队列。
  3137. */
  3138. api.addValidator('fileNumLimit', function () {
  3139. var uploader = this,
  3140. opts = uploader.options,
  3141. count = 0,
  3142. max = opts.fileNumLimit >> 0,
  3143. flag = true;
  3144. if (!max) {
  3145. return;
  3146. }
  3147. uploader.on('beforeFileQueued', function (file) {
  3148. if (count >= max && flag) {
  3149. flag = false;
  3150. this.trigger('error', 'Q_EXCEED_NUM_LIMIT', max, file);
  3151. setTimeout(function () {
  3152. flag = true;
  3153. }, 1);
  3154. }
  3155. return count >= max ? false : true;
  3156. });
  3157. uploader.on('fileQueued', function () {
  3158. count++;
  3159. });
  3160. uploader.on('fileDequeued', function () {
  3161. count--;
  3162. });
  3163. uploader.on('uploadFinished', function () {
  3164. count = 0;
  3165. });
  3166. });
  3167. /**
  3168. * @property {int} [fileSizeLimit=undefined]
  3169. * @namespace options
  3170. * @for Uploader
  3171. * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
  3172. */
  3173. api.addValidator('fileSizeLimit', function () {
  3174. var uploader = this,
  3175. opts = uploader.options,
  3176. count = 0,
  3177. max = opts.fileSizeLimit >> 0,
  3178. flag = true;
  3179. if (!max) {
  3180. return;
  3181. }
  3182. uploader.on('beforeFileQueued', function (file) {
  3183. var invalid = count + file.size > max;
  3184. if (invalid && flag) {
  3185. flag = false;
  3186. this.trigger('error', 'Q_EXCEED_SIZE_LIMIT', max, file);
  3187. setTimeout(function () {
  3188. flag = true;
  3189. }, 1);
  3190. }
  3191. return invalid ? false : true;
  3192. });
  3193. uploader.on('fileQueued', function (file) {
  3194. count += file.size;
  3195. });
  3196. uploader.on('fileDequeued', function (file) {
  3197. count -= file.size;
  3198. });
  3199. uploader.on('uploadFinished', function () {
  3200. count = 0;
  3201. });
  3202. });
  3203. /**
  3204. * @property {int} [fileSingleSizeLimit=undefined]
  3205. * @namespace options
  3206. * @for Uploader
  3207. * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
  3208. */
  3209. api.addValidator('fileSingleSizeLimit', function () {
  3210. var uploader = this,
  3211. opts = uploader.options,
  3212. max = opts.fileSingleSizeLimit;
  3213. if (!max) {
  3214. return;
  3215. }
  3216. uploader.on('beforeFileQueued', function (file) {
  3217. if (file.size > max) {
  3218. file.setStatus(WUFile.Status.INVALID, 'exceed_size');
  3219. this.trigger('error', 'F_EXCEED_SIZE', file);
  3220. return false;
  3221. }
  3222. });
  3223. });
  3224. /**
  3225. * @property {int} [duplicate=undefined]
  3226. * @namespace options
  3227. * @for Uploader
  3228. * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key.
  3229. */
  3230. api.addValidator('duplicate', function () {
  3231. var uploader = this,
  3232. opts = uploader.options,
  3233. mapping = {};
  3234. if (opts.duplicate) {
  3235. return;
  3236. }
  3237. function hashString(str) {
  3238. var hash = 0,
  3239. i = 0,
  3240. len = str.length,
  3241. _char;
  3242. for (; i < len; i++) {
  3243. _char = str.charCodeAt(i);
  3244. hash = _char + (hash << 6) + (hash << 16) - hash;
  3245. }
  3246. return hash;
  3247. }
  3248. uploader.on('beforeFileQueued', function (file) {
  3249. var hash = file.__hash || (file.__hash = hashString(file.name +
  3250. file.size + file.lastModifiedDate));
  3251. // 已经重复了
  3252. if (mapping[hash]) {
  3253. this.trigger('error', 'F_DUPLICATE', file);
  3254. return false;
  3255. }
  3256. });
  3257. uploader.on('fileQueued', function (file) {
  3258. var hash = file.__hash;
  3259. hash && (mapping[hash] = true);
  3260. });
  3261. uploader.on('fileDequeued', function (file) {
  3262. var hash = file.__hash;
  3263. hash && (delete mapping[hash]);
  3264. });
  3265. });
  3266. return api;
  3267. });
  3268. /**
  3269. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  3270. */
  3271. define('runtime/compbase', [], function () {
  3272. function CompBase(owner, runtime) {
  3273. this.owner = owner;
  3274. this.options = owner.options;
  3275. this.getRuntime = function () {
  3276. return runtime;
  3277. };
  3278. this.getRuid = function () {
  3279. return runtime.uid;
  3280. };
  3281. this.trigger = function () {
  3282. return owner.trigger.apply(owner, arguments);
  3283. };
  3284. }
  3285. return CompBase;
  3286. });
  3287. /**
  3288. * @fileOverview Html5Runtime
  3289. */
  3290. define('runtime/html5/runtime', [
  3291. 'base',
  3292. 'runtime/runtime',
  3293. 'runtime/compbase'
  3294. ], function (Base, Runtime, CompBase) {
  3295. var type = 'html5',
  3296. components = {};
  3297. function Html5Runtime() {
  3298. var pool = {},
  3299. me = this,
  3300. destory = this.destory;
  3301. Runtime.apply(me, arguments);
  3302. me.type = type;
  3303. // 这个方法的调用者,实际上是RuntimeClient
  3304. me.exec = function (comp, fn/*, args...*/) {
  3305. var client = this,
  3306. uid = client.uid,
  3307. args = Base.slice(arguments, 2),
  3308. instance;
  3309. if (components[comp]) {
  3310. instance = pool[uid] = pool[uid] ||
  3311. new components[comp](client, me);
  3312. if (instance[fn]) {
  3313. return instance[fn].apply(instance, args);
  3314. }
  3315. }
  3316. };
  3317. me.destory = function () {
  3318. // @todo 删除池子中的所有实例
  3319. return destory && destory.apply(this, arguments);
  3320. };
  3321. }
  3322. Base.inherits(Runtime, {
  3323. constructor: Html5Runtime,
  3324. // 不需要连接其他程序,直接执行callback
  3325. init: function () {
  3326. var me = this;
  3327. setTimeout(function () {
  3328. me.trigger('ready');
  3329. }, 1);
  3330. }
  3331. });
  3332. // 注册Components
  3333. Html5Runtime.register = function (name, component) {
  3334. var klass = components[name] = Base.inherits(CompBase, component);
  3335. return klass;
  3336. };
  3337. // 注册html5运行时。
  3338. // 只有在支持的前提下注册。
  3339. if (window.Blob && window.FileReader && window.DataView) {
  3340. Runtime.addRuntime(type, Html5Runtime);
  3341. }
  3342. return Html5Runtime;
  3343. });
  3344. /**
  3345. * @fileOverview Blob Html实现
  3346. */
  3347. define('runtime/html5/blob', [
  3348. 'runtime/html5/runtime',
  3349. 'lib/blob'
  3350. ], function (Html5Runtime, Blob) {
  3351. return Html5Runtime.register('Blob', {
  3352. slice: function (start, end) {
  3353. var blob = this.owner.source,
  3354. slice = blob.slice || blob.webkitSlice || blob.mozSlice;
  3355. blob = slice.call(blob, start, end);
  3356. return new Blob(this.getRuid(), blob);
  3357. }
  3358. });
  3359. });
  3360. /**
  3361. * @fileOverview FilePaste
  3362. */
  3363. define('runtime/html5/dnd', [
  3364. 'base',
  3365. 'runtime/html5/runtime',
  3366. 'lib/file'
  3367. ], function (Base, Html5Runtime, File) {
  3368. var $ = Base.$,
  3369. prefix = 'webuploader-dnd-';
  3370. return Html5Runtime.register('DragAndDrop', {
  3371. init: function () {
  3372. var elem = this.elem = this.options.container;
  3373. this.dragEnterHandler = Base.bindFn(this._dragEnterHandler, this);
  3374. this.dragOverHandler = Base.bindFn(this._dragOverHandler, this);
  3375. this.dragLeaveHandler = Base.bindFn(this._dragLeaveHandler, this);
  3376. this.dropHandler = Base.bindFn(this._dropHandler, this);
  3377. this.dndOver = false;
  3378. elem.on('dragenter', this.dragEnterHandler);
  3379. elem.on('dragover', this.dragOverHandler);
  3380. elem.on('dragleave', this.dragLeaveHandler);
  3381. elem.on('drop', this.dropHandler);
  3382. if (this.options.disableGlobalDnd) {
  3383. $(document).on('dragover', this.dragOverHandler);
  3384. $(document).on('drop', this.dropHandler);
  3385. }
  3386. },
  3387. _dragEnterHandler: function (e) {
  3388. var me = this,
  3389. denied = me._denied || false,
  3390. items;
  3391. e = e.originalEvent || e;
  3392. if (!me.dndOver) {
  3393. me.dndOver = true;
  3394. // 注意只有 chrome 支持。
  3395. items = e.dataTransfer.items;
  3396. if (items && items.length) {
  3397. me._denied = denied = !me.trigger('accept', items);
  3398. }
  3399. me.elem.addClass(prefix + 'over');
  3400. me.elem[denied ? 'addClass' :
  3401. 'removeClass'](prefix + 'denied');
  3402. }
  3403. e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
  3404. return false;
  3405. },
  3406. _dragOverHandler: function (e) {
  3407. // 只处理框内的。
  3408. var parentElem = this.elem.parent().get(0);
  3409. if (parentElem && !$.contains(parentElem, e.currentTarget)) {
  3410. return false;
  3411. }
  3412. clearTimeout(this._leaveTimer);
  3413. this._dragEnterHandler.call(this, e);
  3414. return false;
  3415. },
  3416. _dragLeaveHandler: function () {
  3417. var me = this,
  3418. handler;
  3419. handler = function () {
  3420. me.dndOver = false;
  3421. me.elem.removeClass(prefix + 'over ' + prefix + 'denied');
  3422. };
  3423. clearTimeout(me._leaveTimer);
  3424. me._leaveTimer = setTimeout(handler, 100);
  3425. return false;
  3426. },
  3427. _dropHandler: function (e) {
  3428. var me = this,
  3429. ruid = me.getRuid(),
  3430. parentElem = me.elem.parent().get(0);
  3431. // 只处理框内的。
  3432. if (parentElem && !$.contains(parentElem, e.currentTarget)) {
  3433. return false;
  3434. }
  3435. me._getTansferFiles(e, function (results) {
  3436. me.trigger('drop', $.map(results, function (file) {
  3437. return new File(ruid, file);
  3438. }));
  3439. });
  3440. me.dndOver = false;
  3441. me.elem.removeClass(prefix + 'over');
  3442. return false;
  3443. },
  3444. // 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
  3445. _getTansferFiles: function (e, callback) {
  3446. var results = [],
  3447. promises = [],
  3448. items, files, dataTransfer, file, item, i, len, canAccessFolder;
  3449. e = e.originalEvent || e;
  3450. dataTransfer = e.dataTransfer;
  3451. items = dataTransfer.items;
  3452. files = dataTransfer.files;
  3453. canAccessFolder = !!(items && items[0].webkitGetAsEntry);
  3454. for (i = 0, len = files.length; i < len; i++) {
  3455. file = files[i];
  3456. item = items && items[i];
  3457. if (canAccessFolder && item.webkitGetAsEntry().isDirectory) {
  3458. promises.push(this._traverseDirectoryTree(
  3459. item.webkitGetAsEntry(), results));
  3460. } else {
  3461. results.push(file);
  3462. }
  3463. }
  3464. Base.when.apply(Base, promises).done(function () {
  3465. if (!results.length) {
  3466. return;
  3467. }
  3468. callback(results);
  3469. });
  3470. },
  3471. _traverseDirectoryTree: function (entry, results) {
  3472. var deferred = Base.Deferred(),
  3473. me = this;
  3474. if (entry.isFile) {
  3475. entry.file(function (file) {
  3476. results.push(file);
  3477. deferred.resolve();
  3478. });
  3479. } else if (entry.isDirectory) {
  3480. entry.createReader().readEntries(function (entries) {
  3481. var len = entries.length,
  3482. promises = [],
  3483. arr = [], // 为了保证顺序。
  3484. i;
  3485. for (i = 0; i < len; i++) {
  3486. promises.push(me._traverseDirectoryTree(
  3487. entries[i], arr));
  3488. }
  3489. Base.when.apply(Base, promises).then(function () {
  3490. results.push.apply(results, arr);
  3491. deferred.resolve();
  3492. }, deferred.reject);
  3493. });
  3494. }
  3495. return deferred.promise();
  3496. },
  3497. destroy: function () {
  3498. var elem = this.elem;
  3499. elem.off('dragenter', this.dragEnterHandler);
  3500. elem.off('dragover', this.dragEnterHandler);
  3501. elem.off('dragleave', this.dragLeaveHandler);
  3502. elem.off('drop', this.dropHandler);
  3503. if (this.options.disableGlobalDnd) {
  3504. $(document).off('dragover', this.dragOverHandler);
  3505. $(document).off('drop', this.dropHandler);
  3506. }
  3507. }
  3508. });
  3509. });
  3510. /**
  3511. * @fileOverview FilePaste
  3512. */
  3513. define('runtime/html5/filepaste', [
  3514. 'base',
  3515. 'runtime/html5/runtime',
  3516. 'lib/file'
  3517. ], function (Base, Html5Runtime, File) {
  3518. return Html5Runtime.register('FilePaste', {
  3519. init: function () {
  3520. var opts = this.options,
  3521. elem = this.elem = opts.container,
  3522. accept = '.*',
  3523. arr, i, len, item;
  3524. // accetp的mimeTypes中生成匹配正则。
  3525. if (opts.accept) {
  3526. arr = [];
  3527. for (i = 0, len = opts.accept.length; i < len; i++) {
  3528. item = opts.accept[i].mimeTypes;
  3529. item && arr.push(item);
  3530. }
  3531. if (arr.length) {
  3532. accept = arr.join(',');
  3533. accept = accept.replace(/,/g, '|').replace(/\*/g, '.*');
  3534. }
  3535. }
  3536. this.accept = accept = new RegExp(accept, 'i');
  3537. this.hander = Base.bindFn(this._pasteHander, this);
  3538. elem.on('paste', this.hander);
  3539. },
  3540. _pasteHander: function (e) {
  3541. var allowed = [],
  3542. ruid = this.getRuid(),
  3543. items, item, blob, i, len;
  3544. e = e.originalEvent || e;
  3545. items = e.clipboardData.items;
  3546. for (i = 0, len = items.length; i < len; i++) {
  3547. item = items[i];
  3548. if (item.kind !== 'file' || !(blob = item.getAsFile())) {
  3549. continue;
  3550. }
  3551. allowed.push(new File(ruid, blob));
  3552. }
  3553. if (allowed.length) {
  3554. // 不阻止非文件粘贴(文字粘贴)的事件冒泡
  3555. e.preventDefault();
  3556. e.stopPropagation();
  3557. this.trigger('paste', allowed);
  3558. }
  3559. },
  3560. destroy: function () {
  3561. this.elem.off('paste', this.hander);
  3562. }
  3563. });
  3564. });
  3565. /**
  3566. * @fileOverview FilePicker
  3567. */
  3568. define('runtime/html5/filepicker', [
  3569. 'base',
  3570. 'runtime/html5/runtime'
  3571. ], function (Base, Html5Runtime) {
  3572. var $ = Base.$;
  3573. return Html5Runtime.register('FilePicker', {
  3574. init: function () {
  3575. var container = this.getRuntime().getContainer(),
  3576. me = this,
  3577. owner = me.owner,
  3578. opts = me.options,
  3579. lable = $(document.createElement('label')),
  3580. input = $(document.createElement('input')),
  3581. arr, i, len, mouseHandler;
  3582. input.attr('type', 'file');
  3583. input.attr('name', opts.name);
  3584. input.addClass('webuploader-element-invisible');
  3585. lable.on('click', function () {
  3586. input.trigger('click');
  3587. });
  3588. lable.css({
  3589. opacity: 0,
  3590. width: '100%',
  3591. height: '100%',
  3592. display: 'block',
  3593. cursor: 'pointer',
  3594. background: '#ffffff'
  3595. });
  3596. if (opts.multiple) {
  3597. input.attr('multiple', 'multiple');
  3598. }
  3599. // @todo Firefox不支持单独指定后缀
  3600. if (opts.accept && opts.accept.length > 0) {
  3601. arr = [];
  3602. for (i = 0, len = opts.accept.length; i < len; i++) {
  3603. arr.push(opts.accept[i].mimeTypes);
  3604. }
  3605. input.attr('accept', arr.join(','));
  3606. }
  3607. container.append(input);
  3608. container.append(lable);
  3609. mouseHandler = function (e) {
  3610. owner.trigger(e.type);
  3611. };
  3612. input.on('change', function (e) {
  3613. var fn = arguments.callee,
  3614. clone;
  3615. me.files = e.target.files;
  3616. // reset input
  3617. clone = this.cloneNode(true);
  3618. this.parentNode.replaceChild(clone, this);
  3619. input.off();
  3620. input = $(clone).on('change', fn)
  3621. .on('mouseenter mouseleave', mouseHandler);
  3622. owner.trigger('change');
  3623. });
  3624. lable.on('mouseenter mouseleave', mouseHandler);
  3625. },
  3626. getFiles: function () {
  3627. return this.files;
  3628. },
  3629. destroy: function () {
  3630. // todo
  3631. }
  3632. });
  3633. });
  3634. /**
  3635. * Terms:
  3636. *
  3637. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3638. * @fileOverview Image控件
  3639. */
  3640. define('runtime/html5/util', [
  3641. 'base'
  3642. ], function (Base) {
  3643. var urlAPI = window.createObjectURL && window ||
  3644. window.URL && URL.revokeObjectURL && URL ||
  3645. window.webkitURL,
  3646. createObjectURL = Base.noop,
  3647. revokeObjectURL = createObjectURL;
  3648. if (urlAPI) {
  3649. // 更安全的方式调用,比如android里面就能把context改成其他的对象。
  3650. createObjectURL = function () {
  3651. return urlAPI.createObjectURL.apply(urlAPI, arguments);
  3652. };
  3653. revokeObjectURL = function () {
  3654. return urlAPI.revokeObjectURL.apply(urlAPI, arguments);
  3655. };
  3656. }
  3657. return {
  3658. createObjectURL: createObjectURL,
  3659. revokeObjectURL: revokeObjectURL,
  3660. dataURL2Blob: function (dataURI) {
  3661. var byteStr, intArray, ab, i, mimetype, parts;
  3662. parts = dataURI.split(',');
  3663. if (~parts[0].indexOf('base64')) {
  3664. byteStr = atob(parts[1]);
  3665. } else {
  3666. byteStr = decodeURIComponent(parts[1]);
  3667. }
  3668. ab = new ArrayBuffer(byteStr.length);
  3669. intArray = new Uint8Array(ab);
  3670. for (i = 0; i < byteStr.length; i++) {
  3671. intArray[i] = byteStr.charCodeAt(i);
  3672. }
  3673. mimetype = parts[0].split(':')[1].split(';')[0];
  3674. return this.arrayBufferToBlob(ab, mimetype);
  3675. },
  3676. dataURL2ArrayBuffer: function (dataURI) {
  3677. var byteStr, intArray, i, parts;
  3678. parts = dataURI.split(',');
  3679. if (~parts[0].indexOf('base64')) {
  3680. byteStr = atob(parts[1]);
  3681. } else {
  3682. byteStr = decodeURIComponent(parts[1]);
  3683. }
  3684. intArray = new Uint8Array(byteStr.length);
  3685. for (i = 0; i < byteStr.length; i++) {
  3686. intArray[i] = byteStr.charCodeAt(i);
  3687. }
  3688. return intArray.buffer;
  3689. },
  3690. arrayBufferToBlob: function (buffer, type) {
  3691. var builder = window.BlobBuilder || window.WebKitBlobBuilder,
  3692. bb;
  3693. // android不支持直接new Blob, 只能借助blobbuilder.
  3694. if (builder) {
  3695. bb = new builder();
  3696. bb.append(buffer);
  3697. return bb.getBlob(type);
  3698. }
  3699. return new Blob([buffer], type ? {type: type} : {});
  3700. },
  3701. // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
  3702. // 你得到的结果是png.
  3703. canvasToDataUrl: function (canvas, type, quality) {
  3704. return canvas.toDataURL(type, quality / 100);
  3705. },
  3706. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3707. parseMeta: function (blob, callback) {
  3708. callback(false, {});
  3709. },
  3710. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3711. updateImageHead: function (data) {
  3712. return data;
  3713. }
  3714. };
  3715. });
  3716. /**
  3717. * Terms:
  3718. *
  3719. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3720. * @fileOverview Image控件
  3721. */
  3722. define('runtime/html5/imagemeta', [
  3723. 'runtime/html5/util'
  3724. ], function (Util) {
  3725. var api;
  3726. api = {
  3727. parsers: {
  3728. 0xffe1: []
  3729. },
  3730. maxMetaDataSize: 262144,
  3731. parse: function (blob, cb) {
  3732. var me = this,
  3733. fr = new FileReader();
  3734. fr.onload = function () {
  3735. cb(false, me._parse(this.result));
  3736. fr = fr.onload = fr.onerror = null;
  3737. };
  3738. fr.onerror = function (e) {
  3739. cb(e.message);
  3740. fr = fr.onload = fr.onerror = null;
  3741. };
  3742. blob = blob.slice(0, me.maxMetaDataSize);
  3743. fr.readAsArrayBuffer(blob.getSource());
  3744. },
  3745. _parse: function (buffer, noParse) {
  3746. if (buffer.byteLength < 6) {
  3747. return;
  3748. }
  3749. var dataview = new DataView(buffer),
  3750. offset = 2,
  3751. maxOffset = dataview.byteLength - 4,
  3752. headLength = offset,
  3753. ret = {},
  3754. markerBytes, markerLength, parsers, i;
  3755. if (dataview.getUint16(0) === 0xffd8) {
  3756. while (offset < maxOffset) {
  3757. markerBytes = dataview.getUint16(offset);
  3758. if (markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
  3759. markerBytes === 0xfffe) {
  3760. markerLength = dataview.getUint16(offset + 2) + 2;
  3761. if (offset + markerLength > dataview.byteLength) {
  3762. break;
  3763. }
  3764. parsers = api.parsers[markerBytes];
  3765. if (!noParse && parsers) {
  3766. for (i = 0; i < parsers.length; i += 1) {
  3767. parsers[i].call(api, dataview, offset,
  3768. markerLength, ret);
  3769. }
  3770. }
  3771. offset += markerLength;
  3772. headLength = offset;
  3773. } else {
  3774. break;
  3775. }
  3776. }
  3777. if (headLength > 6) {
  3778. if (buffer.slice) {
  3779. ret.imageHead = buffer.slice(2, headLength);
  3780. } else {
  3781. // Workaround for IE10, which does not yet
  3782. // support ArrayBuffer.slice:
  3783. ret.imageHead = new Uint8Array(buffer)
  3784. .subarray(2, headLength);
  3785. }
  3786. }
  3787. }
  3788. return ret;
  3789. },
  3790. updateImageHead: function (buffer, head) {
  3791. var data = this._parse(buffer, true),
  3792. buf1, buf2, bodyoffset;
  3793. bodyoffset = 2;
  3794. if (data.imageHead) {
  3795. bodyoffset = 2 + data.imageHead.byteLength;
  3796. }
  3797. if (buffer.slice) {
  3798. buf2 = buffer.slice(bodyoffset);
  3799. } else {
  3800. buf2 = new Uint8Array(buffer).subarray(bodyoffset);
  3801. }
  3802. buf1 = new Uint8Array(head.byteLength + 2 + buf2.byteLength);
  3803. buf1[0] = 0xFF;
  3804. buf1[1] = 0xD8;
  3805. buf1.set(new Uint8Array(head), 2);
  3806. buf1.set(new Uint8Array(buf2), head.byteLength + 2);
  3807. return buf1.buffer;
  3808. }
  3809. };
  3810. Util.parseMeta = function () {
  3811. return api.parse.apply(api, arguments);
  3812. };
  3813. Util.updateImageHead = function () {
  3814. return api.updateImageHead.apply(api, arguments);
  3815. };
  3816. return api;
  3817. });
  3818. /**
  3819. * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
  3820. * 暂时项目中只用了orientation.
  3821. *
  3822. * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
  3823. * @fileOverview EXIF解析
  3824. */
  3825. // Sample
  3826. // ====================================
  3827. // Make : Apple
  3828. // Model : iPhone 4S
  3829. // Orientation : 1
  3830. // XResolution : 72 [72/1]
  3831. // YResolution : 72 [72/1]
  3832. // ResolutionUnit : 2
  3833. // Software : QuickTime 7.7.1
  3834. // DateTime : 2013:09:01 22:53:55
  3835. // ExifIFDPointer : 190
  3836. // ExposureTime : 0.058823529411764705 [1/17]
  3837. // FNumber : 2.4 [12/5]
  3838. // ExposureProgram : Normal program
  3839. // ISOSpeedRatings : 800
  3840. // ExifVersion : 0220
  3841. // DateTimeOriginal : 2013:09:01 22:52:51
  3842. // DateTimeDigitized : 2013:09:01 22:52:51
  3843. // ComponentsConfiguration : YCbCr
  3844. // ShutterSpeedValue : 4.058893515764426
  3845. // ApertureValue : 2.5260688216892597 [4845/1918]
  3846. // BrightnessValue : -0.3126686601998395
  3847. // MeteringMode : Pattern
  3848. // Flash : Flash did not fire, compulsory flash mode
  3849. // FocalLength : 4.28 [107/25]
  3850. // SubjectArea : [4 values]
  3851. // FlashpixVersion : 0100
  3852. // ColorSpace : 1
  3853. // PixelXDimension : 2448
  3854. // PixelYDimension : 3264
  3855. // SensingMethod : One-chip color area sensor
  3856. // ExposureMode : 0
  3857. // WhiteBalance : Auto white balance
  3858. // FocalLengthIn35mmFilm : 35
  3859. // SceneCaptureType : Standard
  3860. define('runtime/html5/imagemeta/exif', [
  3861. 'base',
  3862. 'runtime/html5/imagemeta'
  3863. ], function (Base, ImageMeta) {
  3864. var EXIF = {};
  3865. EXIF.ExifMap = function () {
  3866. return this;
  3867. };
  3868. EXIF.ExifMap.prototype.map = {
  3869. 'Orientation': 0x0112
  3870. };
  3871. EXIF.ExifMap.prototype.get = function (id) {
  3872. return this[id] || this[this.map[id]];
  3873. };
  3874. EXIF.exifTagTypes = {
  3875. // byte, 8-bit unsigned int:
  3876. 1: {
  3877. getValue: function (dataView, dataOffset) {
  3878. return dataView.getUint8(dataOffset);
  3879. },
  3880. size: 1
  3881. },
  3882. // ascii, 8-bit byte:
  3883. 2: {
  3884. getValue: function (dataView, dataOffset) {
  3885. return String.fromCharCode(dataView.getUint8(dataOffset));
  3886. },
  3887. size: 1,
  3888. ascii: true
  3889. },
  3890. // short, 16 bit int:
  3891. 3: {
  3892. getValue: function (dataView, dataOffset, littleEndian) {
  3893. return dataView.getUint16(dataOffset, littleEndian);
  3894. },
  3895. size: 2
  3896. },
  3897. // long, 32 bit int:
  3898. 4: {
  3899. getValue: function (dataView, dataOffset, littleEndian) {
  3900. return dataView.getUint32(dataOffset, littleEndian);
  3901. },
  3902. size: 4
  3903. },
  3904. // rational = two long values,
  3905. // first is numerator, second is denominator:
  3906. 5: {
  3907. getValue: function (dataView, dataOffset, littleEndian) {
  3908. return dataView.getUint32(dataOffset, littleEndian) /
  3909. dataView.getUint32(dataOffset + 4, littleEndian);
  3910. },
  3911. size: 8
  3912. },
  3913. // slong, 32 bit signed int:
  3914. 9: {
  3915. getValue: function (dataView, dataOffset, littleEndian) {
  3916. return dataView.getInt32(dataOffset, littleEndian);
  3917. },
  3918. size: 4
  3919. },
  3920. // srational, two slongs, first is numerator, second is denominator:
  3921. 10: {
  3922. getValue: function (dataView, dataOffset, littleEndian) {
  3923. return dataView.getInt32(dataOffset, littleEndian) /
  3924. dataView.getInt32(dataOffset + 4, littleEndian);
  3925. },
  3926. size: 8
  3927. }
  3928. };
  3929. // undefined, 8-bit byte, value depending on field:
  3930. EXIF.exifTagTypes[7] = EXIF.exifTagTypes[1];
  3931. EXIF.getExifValue = function (dataView, tiffOffset, offset, type, length,
  3932. littleEndian) {
  3933. var tagType = EXIF.exifTagTypes[type],
  3934. tagSize, dataOffset, values, i, str, c;
  3935. if (!tagType) {
  3936. Base.log('Invalid Exif data: Invalid tag type.');
  3937. return;
  3938. }
  3939. tagSize = tagType.size * length;
  3940. // Determine if the value is contained in the dataOffset bytes,
  3941. // or if the value at the dataOffset is a pointer to the actual data:
  3942. dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32(offset + 8,
  3943. littleEndian) : (offset + 8);
  3944. if (dataOffset + tagSize > dataView.byteLength) {
  3945. Base.log('Invalid Exif data: Invalid data offset.');
  3946. return;
  3947. }
  3948. if (length === 1) {
  3949. return tagType.getValue(dataView, dataOffset, littleEndian);
  3950. }
  3951. values = [];
  3952. for (i = 0; i < length; i += 1) {
  3953. values[i] = tagType.getValue(dataView,
  3954. dataOffset + i * tagType.size, littleEndian);
  3955. }
  3956. if (tagType.ascii) {
  3957. str = '';
  3958. // Concatenate the chars:
  3959. for (i = 0; i < values.length; i += 1) {
  3960. c = values[i];
  3961. // Ignore the terminating NULL byte(s):
  3962. if (c === '\u0000') {
  3963. break;
  3964. }
  3965. str += c;
  3966. }
  3967. return str;
  3968. }
  3969. return values;
  3970. };
  3971. EXIF.parseExifTag = function (dataView, tiffOffset, offset, littleEndian,
  3972. data) {
  3973. var tag = dataView.getUint16(offset, littleEndian);
  3974. data.exif[tag] = EXIF.getExifValue(dataView, tiffOffset, offset,
  3975. dataView.getUint16(offset + 2, littleEndian), // tag type
  3976. dataView.getUint32(offset + 4, littleEndian), // tag length
  3977. littleEndian);
  3978. };
  3979. EXIF.parseExifTags = function (dataView, tiffOffset, dirOffset,
  3980. littleEndian, data) {
  3981. var tagsNumber, dirEndOffset, i;
  3982. if (dirOffset + 6 > dataView.byteLength) {
  3983. Base.log('Invalid Exif data: Invalid directory offset.');
  3984. return;
  3985. }
  3986. tagsNumber = dataView.getUint16(dirOffset, littleEndian);
  3987. dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
  3988. if (dirEndOffset + 4 > dataView.byteLength) {
  3989. Base.log('Invalid Exif data: Invalid directory size.');
  3990. return;
  3991. }
  3992. for (i = 0; i < tagsNumber; i += 1) {
  3993. this.parseExifTag(dataView, tiffOffset,
  3994. dirOffset + 2 + 12 * i, // tag offset
  3995. littleEndian, data);
  3996. }
  3997. // Return the offset to the next directory:
  3998. return dataView.getUint32(dirEndOffset, littleEndian);
  3999. };
  4000. // EXIF.getExifThumbnail = function(dataView, offset, length) {
  4001. // var hexData,
  4002. // i,
  4003. // b;
  4004. // if (!length || offset + length > dataView.byteLength) {
  4005. // Base.log('Invalid Exif data: Invalid thumbnail data.');
  4006. // return;
  4007. // }
  4008. // hexData = [];
  4009. // for (i = 0; i < length; i += 1) {
  4010. // b = dataView.getUint8(offset + i);
  4011. // hexData.push((b < 16 ? '0' : '') + b.toString(16));
  4012. // }
  4013. // return 'data:image/jpeg,%' + hexData.join('%');
  4014. // };
  4015. EXIF.parseExifData = function (dataView, offset, length, data) {
  4016. var tiffOffset = offset + 10,
  4017. littleEndian, dirOffset;
  4018. // Check for the ASCII code for "Exif" (0x45786966):
  4019. if (dataView.getUint32(offset + 4) !== 0x45786966) {
  4020. // No Exif data, might be XMP data instead
  4021. return;
  4022. }
  4023. if (tiffOffset + 8 > dataView.byteLength) {
  4024. Base.log('Invalid Exif data: Invalid segment size.');
  4025. return;
  4026. }
  4027. // Check for the two null bytes:
  4028. if (dataView.getUint16(offset + 8) !== 0x0000) {
  4029. Base.log('Invalid Exif data: Missing byte alignment offset.');
  4030. return;
  4031. }
  4032. // Check the byte alignment:
  4033. switch (dataView.getUint16(tiffOffset)) {
  4034. case 0x4949:
  4035. littleEndian = true;
  4036. break;
  4037. case 0x4D4D:
  4038. littleEndian = false;
  4039. break;
  4040. default:
  4041. Base.log('Invalid Exif data: Invalid byte alignment marker.');
  4042. return;
  4043. }
  4044. // Check for the TIFF tag marker (0x002A):
  4045. if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
  4046. Base.log('Invalid Exif data: Missing TIFF marker.');
  4047. return;
  4048. }
  4049. // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
  4050. dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
  4051. // Create the exif object to store the tags:
  4052. data.exif = new EXIF.ExifMap();
  4053. // Parse the tags of the main image directory and retrieve the
  4054. // offset to the next directory, usually the thumbnail directory:
  4055. dirOffset = EXIF.parseExifTags(dataView, tiffOffset,
  4056. tiffOffset + dirOffset, littleEndian, data);
  4057. // 尝试读取缩略图
  4058. // if ( dirOffset ) {
  4059. // thumbnailData = {exif: {}};
  4060. // dirOffset = EXIF.parseExifTags(
  4061. // dataView,
  4062. // tiffOffset,
  4063. // tiffOffset + dirOffset,
  4064. // littleEndian,
  4065. // thumbnailData
  4066. // );
  4067. // // Check for JPEG Thumbnail offset:
  4068. // if (thumbnailData.exif[0x0201]) {
  4069. // data.exif.Thumbnail = EXIF.getExifThumbnail(
  4070. // dataView,
  4071. // tiffOffset + thumbnailData.exif[0x0201],
  4072. // thumbnailData.exif[0x0202] // Thumbnail data length
  4073. // );
  4074. // }
  4075. // }
  4076. };
  4077. ImageMeta.parsers[0xffe1].push(EXIF.parseExifData);
  4078. return EXIF;
  4079. });
  4080. /**
  4081. * @fileOverview Image
  4082. */
  4083. define('runtime/html5/image', [
  4084. 'base',
  4085. 'runtime/html5/runtime',
  4086. 'runtime/html5/util'
  4087. ], function (Base, Html5Runtime, Util) {
  4088. var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
  4089. return Html5Runtime.register('Image', {
  4090. // flag: 标记是否被修改过。
  4091. modified: false,
  4092. init: function () {
  4093. var me = this,
  4094. img = new Image();
  4095. img.onload = function () {
  4096. me._info = {
  4097. type: me.type,
  4098. width: this.width,
  4099. height: this.height
  4100. };
  4101. // 读取meta信息。
  4102. if (!me._metas && 'image/jpeg' === me.type) {
  4103. Util.parseMeta(me._blob, function (error, ret) {
  4104. me._metas = ret;
  4105. me.owner.trigger('load');
  4106. });
  4107. } else {
  4108. me.owner.trigger('load');
  4109. }
  4110. };
  4111. img.onerror = function () {
  4112. me.owner.trigger('error');
  4113. };
  4114. me._img = img;
  4115. },
  4116. loadFromBlob: function (blob) {
  4117. var me = this,
  4118. img = me._img;
  4119. me._blob = blob;
  4120. me.type = blob.type;
  4121. img.src = Util.createObjectURL(blob.getSource());
  4122. me.owner.once('load', function () {
  4123. Util.revokeObjectURL(img.src);
  4124. });
  4125. },
  4126. resize: function (width, height) {
  4127. var canvas = this._canvas ||
  4128. (this._canvas = document.createElement('canvas'));
  4129. this._resize(this._img, canvas, width, height);
  4130. this._blob = null; // 没用了,可以删掉了。
  4131. this.modified = true;
  4132. this.owner.trigger('complete');
  4133. },
  4134. getAsBlob: function (type) {
  4135. var blob = this._blob,
  4136. opts = this.options,
  4137. canvas;
  4138. type = type || this.type;
  4139. // blob需要重新生成。
  4140. if (this.modified || this.type !== type) {
  4141. canvas = this._canvas;
  4142. if (type === 'image/jpeg') {
  4143. blob = Util.canvasToDataUrl(canvas, 'image/jpeg',
  4144. opts.quality);
  4145. if (opts.preserveHeaders && this._metas &&
  4146. this._metas.imageHead) {
  4147. blob = Util.dataURL2ArrayBuffer(blob);
  4148. blob = Util.updateImageHead(blob,
  4149. this._metas.imageHead);
  4150. blob = Util.arrayBufferToBlob(blob, type);
  4151. return blob;
  4152. }
  4153. } else {
  4154. blob = Util.canvasToDataUrl(canvas, type);
  4155. }
  4156. blob = Util.dataURL2Blob(blob);
  4157. }
  4158. return blob;
  4159. },
  4160. getAsDataUrl: function (type) {
  4161. var opts = this.options;
  4162. type = type || this.type;
  4163. if (type === 'image/jpeg') {
  4164. return Util.canvasToDataUrl(this._canvas, type, opts.quality);
  4165. } else {
  4166. return this._canvas.toDataURL(type);
  4167. }
  4168. },
  4169. getOrientation: function () {
  4170. return this._metas && this._metas.exif &&
  4171. this._metas.exif.get('Orientation') || 1;
  4172. },
  4173. info: function (val) {
  4174. // setter
  4175. if (val) {
  4176. this._info = val;
  4177. return this;
  4178. }
  4179. // getter
  4180. return this._info;
  4181. },
  4182. meta: function (val) {
  4183. // setter
  4184. if (val) {
  4185. this._meta = val;
  4186. return this;
  4187. }
  4188. // getter
  4189. return this._meta;
  4190. },
  4191. destroy: function () {
  4192. var canvas = this._canvas;
  4193. this._img.onload = null;
  4194. if (canvas) {
  4195. canvas.getContext('2d')
  4196. .clearRect(0, 0, canvas.width, canvas.height);
  4197. canvas.width = canvas.height = 0;
  4198. this._canvas = null;
  4199. }
  4200. // 释放内存。非常重要,否则释放不了image的内存。
  4201. this._img.src = BLANK;
  4202. this._img = this._blob = null;
  4203. },
  4204. _resize: function (img, cvs, width, height) {
  4205. var opts = this.options,
  4206. naturalWidth = img.width,
  4207. naturalHeight = img.height,
  4208. orientation = this.getOrientation(),
  4209. scale, w, h, x, y;
  4210. // values that require 90 degree rotation
  4211. if (~[5, 6, 7, 8].indexOf(orientation)) {
  4212. // 交换width, height的值。
  4213. width ^= height;
  4214. height ^= width;
  4215. width ^= height;
  4216. }
  4217. scale = Math[opts.crop ? 'max' : 'min'](width / naturalWidth,
  4218. height / naturalHeight);
  4219. // 不允许放大。
  4220. opts.allowMagnify || (scale = Math.min(1, scale));
  4221. w = naturalWidth * scale;
  4222. h = naturalHeight * scale;
  4223. if (opts.crop) {
  4224. cvs.width = width;
  4225. cvs.height = height;
  4226. } else {
  4227. cvs.width = w;
  4228. cvs.height = h;
  4229. }
  4230. x = (cvs.width - w) / 2;
  4231. y = (cvs.height - h) / 2;
  4232. opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation);
  4233. this._renderImageToCanvas(cvs, img, x, y, w, h);
  4234. },
  4235. _rotate2Orientaion: function (canvas, orientation) {
  4236. var width = canvas.width,
  4237. height = canvas.height,
  4238. ctx = canvas.getContext('2d');
  4239. switch (orientation) {
  4240. case 5:
  4241. case 6:
  4242. case 7:
  4243. case 8:
  4244. canvas.width = height;
  4245. canvas.height = width;
  4246. break;
  4247. }
  4248. switch (orientation) {
  4249. case 2: // horizontal flip
  4250. ctx.translate(width, 0);
  4251. ctx.scale(-1, 1);
  4252. break;
  4253. case 3: // 180 rotate left
  4254. ctx.translate(width, height);
  4255. ctx.rotate(Math.PI);
  4256. break;
  4257. case 4: // vertical flip
  4258. ctx.translate(0, height);
  4259. ctx.scale(1, -1);
  4260. break;
  4261. case 5: // vertical flip + 90 rotate right
  4262. ctx.rotate(0.5 * Math.PI);
  4263. ctx.scale(1, -1);
  4264. break;
  4265. case 6: // 90 rotate right
  4266. ctx.rotate(0.5 * Math.PI);
  4267. ctx.translate(0, -height);
  4268. break;
  4269. case 7: // horizontal flip + 90 rotate right
  4270. ctx.rotate(0.5 * Math.PI);
  4271. ctx.translate(width, -height);
  4272. ctx.scale(-1, 1);
  4273. break;
  4274. case 8: // 90 rotate left
  4275. ctx.rotate(-0.5 * Math.PI);
  4276. ctx.translate(-width, 0);
  4277. break;
  4278. }
  4279. },
  4280. // https://github.com/stomita/ios-imagefile-megapixel/
  4281. // blob/master/src/megapix-image.js
  4282. _renderImageToCanvas: (function () {
  4283. // 如果不是ios, 不需要这么复杂!
  4284. if (!Base.os.ios) {
  4285. return function (canvas, img, x, y, w, h) {
  4286. canvas.getContext('2d').drawImage(img, x, y, w, h);
  4287. };
  4288. }
  4289. /**
  4290. * Detecting vertical squash in loaded image.
  4291. * Fixes a bug which squash image vertically while drawing into
  4292. * canvas for some images.
  4293. */
  4294. function detectVerticalSquash(img, iw, ih) {
  4295. var canvas = document.createElement('canvas'),
  4296. ctx = canvas.getContext('2d'),
  4297. sy = 0,
  4298. ey = ih,
  4299. py = ih,
  4300. data, alpha, ratio;
  4301. canvas.width = 1;
  4302. canvas.height = ih;
  4303. ctx.drawImage(img, 0, 0);
  4304. data = ctx.getImageData(0, 0, 1, ih).data;
  4305. // search image edge pixel position in case
  4306. // it is squashed vertically.
  4307. while (py > sy) {
  4308. alpha = data[(py - 1) * 4 + 3];
  4309. if (alpha === 0) {
  4310. ey = py;
  4311. } else {
  4312. sy = py;
  4313. }
  4314. py = (ey + sy) >> 1;
  4315. }
  4316. ratio = (py / ih);
  4317. return (ratio === 0) ? 1 : ratio;
  4318. }
  4319. // fix ie7 bug
  4320. // http://stackoverflow.com/questions/11929099/
  4321. // html5-canvas-drawimage-ratio-bug-ios
  4322. if (Base.os.ios >= 7) {
  4323. return function (canvas, img, x, y, w, h) {
  4324. var iw = img.naturalWidth,
  4325. ih = img.naturalHeight,
  4326. vertSquashRatio = detectVerticalSquash(img, iw, ih);
  4327. return canvas.getContext('2d').drawImage(img, 0, 0,
  4328. iw * vertSquashRatio, ih * vertSquashRatio,
  4329. x, y, w, h);
  4330. };
  4331. }
  4332. /**
  4333. * Detect subsampling in loaded image.
  4334. * In iOS, larger images than 2M pixels may be
  4335. * subsampled in rendering.
  4336. */
  4337. function detectSubsampling(img) {
  4338. var iw = img.naturalWidth,
  4339. ih = img.naturalHeight,
  4340. canvas, ctx;
  4341. // subsampling may happen overmegapixel image
  4342. if (iw * ih > 1024 * 1024) {
  4343. canvas = document.createElement('canvas');
  4344. canvas.width = canvas.height = 1;
  4345. ctx = canvas.getContext('2d');
  4346. ctx.drawImage(img, -iw + 1, 0);
  4347. // subsampled image becomes half smaller in rendering size.
  4348. // check alpha channel value to confirm image is covering
  4349. // edge pixel or not. if alpha value is 0
  4350. // image is not covering, hence subsampled.
  4351. return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
  4352. } else {
  4353. return false;
  4354. }
  4355. }
  4356. return function (canvas, img, x, y, width, height) {
  4357. var iw = img.naturalWidth,
  4358. ih = img.naturalHeight,
  4359. ctx = canvas.getContext('2d'),
  4360. subsampled = detectSubsampling(img),
  4361. doSquash = this.type === 'image/jpeg',
  4362. d = 1024,
  4363. sy = 0,
  4364. dy = 0,
  4365. tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
  4366. if (subsampled) {
  4367. iw /= 2;
  4368. ih /= 2;
  4369. }
  4370. ctx.save();
  4371. tmpCanvas = document.createElement('canvas');
  4372. tmpCanvas.width = tmpCanvas.height = d;
  4373. tmpCtx = tmpCanvas.getContext('2d');
  4374. vertSquashRatio = doSquash ?
  4375. detectVerticalSquash(img, iw, ih) : 1;
  4376. dw = Math.ceil(d * width / iw);
  4377. dh = Math.ceil(d * height / ih / vertSquashRatio);
  4378. while (sy < ih) {
  4379. sx = 0;
  4380. dx = 0;
  4381. while (sx < iw) {
  4382. tmpCtx.clearRect(0, 0, d, d);
  4383. tmpCtx.drawImage(img, -sx, -sy);
  4384. ctx.drawImage(tmpCanvas, 0, 0, d, d,
  4385. x + dx, y + dy, dw, dh);
  4386. sx += d;
  4387. dx += dw;
  4388. }
  4389. sy += d;
  4390. dy += dh;
  4391. }
  4392. ctx.restore();
  4393. tmpCanvas = tmpCtx = null;
  4394. };
  4395. })()
  4396. });
  4397. });
  4398. /**
  4399. * @fileOverview Transport
  4400. * @todo 支持chunked传输,优势:
  4401. * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
  4402. * 而不需要重头再传一次。另外断点续传也需要用chunked方式。
  4403. */
  4404. define('runtime/html5/transport', [
  4405. 'base',
  4406. 'runtime/html5/runtime'
  4407. ], function (Base, Html5Runtime) {
  4408. var noop = Base.noop,
  4409. $ = Base.$;
  4410. return Html5Runtime.register('Transport', {
  4411. init: function () {
  4412. this._status = 0;
  4413. this._response = null;
  4414. },
  4415. send: function () {
  4416. var owner = this.owner,
  4417. opts = this.options,
  4418. xhr = this._initAjax(),
  4419. blob = owner._blob,
  4420. server = opts.server,
  4421. formData, binary, fr;
  4422. if (opts.sendAsBinary) {
  4423. server += (/\?/.test(server) ? '&' : '?') +
  4424. $.param(owner._formData);
  4425. binary = blob.getSource();
  4426. } else {
  4427. formData = new FormData();
  4428. $.each(owner._formData, function (k, v) {
  4429. formData.append(k, v);
  4430. });
  4431. formData.append(opts.fileVal, blob.getSource(),
  4432. opts.filename || owner._formData.name || '');
  4433. }
  4434. if (opts.withCredentials && 'withCredentials' in xhr) {
  4435. xhr.open(opts.method, server, true);
  4436. xhr.withCredentials = true;
  4437. } else {
  4438. xhr.open(opts.method, server);
  4439. }
  4440. this._setRequestHeader(xhr, opts.headers);
  4441. if (binary) {
  4442. xhr.overrideMimeType('application/octet-stream');
  4443. // android直接发送blob会导致服务端接收到的是空文件。
  4444. // bug详情。
  4445. // https://code.google.com/p/android/issues/detail?id=39882
  4446. // 所以先用fileReader读取出来再通过arraybuffer的方式发送。
  4447. if (Base.os.android) {
  4448. fr = new FileReader();
  4449. fr.onload = function () {
  4450. xhr.send(this.result);
  4451. fr = fr.onload = null;
  4452. };
  4453. fr.readAsArrayBuffer(binary);
  4454. } else {
  4455. xhr.send(binary);
  4456. }
  4457. } else {
  4458. xhr.send(formData);
  4459. }
  4460. },
  4461. getResponse: function () {
  4462. return this._response;
  4463. },
  4464. getResponseAsJson: function () {
  4465. return this._parseJson(this._response);
  4466. },
  4467. getStatus: function () {
  4468. return this._status;
  4469. },
  4470. abort: function () {
  4471. var xhr = this._xhr;
  4472. if (xhr) {
  4473. xhr.upload.onprogress = noop;
  4474. xhr.onreadystatechange = noop;
  4475. xhr.abort();
  4476. this._xhr = xhr = null;
  4477. }
  4478. },
  4479. destroy: function () {
  4480. this.abort();
  4481. },
  4482. _initAjax: function () {
  4483. var me = this,
  4484. xhr = new XMLHttpRequest(),
  4485. opts = this.options;
  4486. if (opts.withCredentials && !('withCredentials' in xhr) &&
  4487. typeof XDomainRequest !== 'undefined') {
  4488. xhr = new XDomainRequest();
  4489. }
  4490. xhr.upload.onprogress = function (e) {
  4491. var percentage = 0;
  4492. if (e.lengthComputable) {
  4493. percentage = e.loaded / e.total;
  4494. }
  4495. return me.trigger('progress', percentage);
  4496. };
  4497. xhr.onreadystatechange = function () {
  4498. if (xhr.readyState !== 4) {
  4499. return;
  4500. }
  4501. xhr.upload.onprogress = noop;
  4502. xhr.onreadystatechange = noop;
  4503. me._xhr = null;
  4504. me._status = xhr.status;
  4505. if (xhr.status >= 200 && xhr.status < 300) {
  4506. me._response = xhr.responseText;
  4507. return me.trigger('load');
  4508. } else if (xhr.status >= 500 && xhr.status < 600) {
  4509. me._response = xhr.responseText;
  4510. return me.trigger('error', 'server');
  4511. }
  4512. return me.trigger('error', me._status ? 'http' : 'abort');
  4513. };
  4514. me._xhr = xhr;
  4515. return xhr;
  4516. },
  4517. _setRequestHeader: function (xhr, headers) {
  4518. $.each(headers, function (key, val) {
  4519. xhr.setRequestHeader(key, val);
  4520. });
  4521. },
  4522. _parseJson: function (str) {
  4523. var json;
  4524. try {
  4525. json = JSON.parse(str);
  4526. } catch (ex) {
  4527. json = {};
  4528. }
  4529. return json;
  4530. }
  4531. });
  4532. });
  4533. /**
  4534. * @fileOverview 只有html5实现的文件版本。
  4535. */
  4536. define('preset/html5only', [
  4537. 'base',
  4538. // widgets
  4539. 'widgets/filednd',
  4540. 'widgets/filepaste',
  4541. 'widgets/filepicker',
  4542. 'widgets/image',
  4543. 'widgets/queue',
  4544. 'widgets/runtime',
  4545. 'widgets/upload',
  4546. 'widgets/validator',
  4547. // runtimes
  4548. // html5
  4549. 'runtime/html5/blob',
  4550. 'runtime/html5/dnd',
  4551. 'runtime/html5/filepaste',
  4552. 'runtime/html5/filepicker',
  4553. 'runtime/html5/imagemeta/exif',
  4554. 'runtime/html5/image',
  4555. 'runtime/html5/transport'
  4556. ], function (Base) {
  4557. return Base;
  4558. });
  4559. define('webuploader', [
  4560. 'preset/html5only'
  4561. ], function (preset) {
  4562. return preset;
  4563. });
  4564. return require('webuploader');
  4565. });