webuploader.html5only.js 147 KB

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