fileinput.js 291 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397
  1. /*!
  2. * bootstrap-fileinput v5.2.4
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD-3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. 'use strict';
  13. if (typeof define === 'function' && define.amd) {
  14. define(['jquery'], factory);
  15. } else {
  16. if (typeof module === 'object' && module.exports) {
  17. //noinspection NpmUsedModulesInstalled
  18. module.exports = factory(require('jquery'));
  19. } else {
  20. factory(window.jQuery);
  21. }
  22. }
  23. }(function ($) {
  24. 'use strict';
  25. $.fn.fileinputLocales = {};
  26. $.fn.fileinputThemes = {};
  27. if (!$.fn.fileinputBsVersion) {
  28. $.fn.fileinputBsVersion = (window.Alert && window.Alert.VERSION) ||
  29. (window.bootstrap && window.bootstrap.Alert && bootstrap.Alert.VERSION) || '3.x.x';
  30. }
  31. String.prototype.setTokens = function (replacePairs) {
  32. var str = this.toString(), key, re;
  33. for (key in replacePairs) {
  34. if (replacePairs.hasOwnProperty(key)) {
  35. re = new RegExp('\{' + key + '\}', 'g');
  36. str = str.replace(re, replacePairs[key]);
  37. }
  38. }
  39. return str;
  40. };
  41. if (!Array.prototype.flatMap) { // polyfill flatMap
  42. Array.prototype.flatMap = function (lambda) {
  43. return [].concat(this.map(lambda));
  44. };
  45. }
  46. var $h, FileInput, getLoadingUrl = function () {
  47. var src = document.currentScript.src, srcPath = src.substring(0, src.lastIndexOf("/"));
  48. return srcPath + '/loading.gif'
  49. };
  50. // fileinput helper object for all global variables and internal helper methods
  51. $h = {
  52. FRAMES: '.kv-preview-thumb',
  53. SORT_CSS: 'file-sortable',
  54. INIT_FLAG: 'init-',
  55. ZOOM_VAR: getLoadingUrl() + '?kvTemp__2873389129__=', // used to prevent 404 errors in URL parsing
  56. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  57. '<param name="allowFullScreen" value="true" />\n' +
  58. '<param name="allowScriptAccess" value="always" />\n' +
  59. '<param name="autoPlay" value="false" />\n' +
  60. '<param name="autoStart" value="false" />\n' +
  61. '<param name="quality" value="high" />\n',
  62. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  63. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  64. '</div>',
  65. MODAL_ID: 'kvFileinputModal',
  66. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  67. logMessages: {
  68. ajaxError: '{status}: {error}. Error Details: {text}.',
  69. badDroppedFiles: 'Error scanning dropped files!',
  70. badExifParser: 'Error loading the piexif.js library. {details}',
  71. badInputType: 'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',
  72. exifWarning: 'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded ' +
  73. 'the "piexif.js" library correctly on your page before the "fileinput.js" script.',
  74. invalidChunkSize: 'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',
  75. invalidThumb: 'Invalid thumb frame with id: "{id}".',
  76. noResumableSupport: 'The browser does not support resumable or chunk uploads.',
  77. noUploadUrl: 'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',
  78. retryStatus: 'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.',
  79. chunkQueueError: 'Could not push task to ajax pool for chunk index # {index}.',
  80. resumableMaxRetriesReached: 'Maximum resumable ajax retries ({n}) reached.',
  81. resumableRetryError: 'Could not retry the resumable request (try # {n})... aborting.',
  82. resumableAborting: 'Aborting / cancelling the resumable request.',
  83. resumableRequestError: 'Error processing resumable request. {msg}'
  84. },
  85. objUrl: window.URL || window.webkitURL,
  86. isBs: function (ver) {
  87. var chk = $.trim(($.fn.fileinputBsVersion || '') + '');
  88. ver = parseInt(ver, 10);
  89. if (!chk) {
  90. return ver === 4;
  91. }
  92. return ver === parseInt(chk.charAt(0), 10);
  93. },
  94. defaultButtonCss: function (fill) {
  95. return 'btn-default btn-' + (fill ? '' : 'outline-') + 'secondary';
  96. },
  97. now: function () {
  98. return new Date().getTime();
  99. },
  100. round: function (num) {
  101. num = parseFloat(num);
  102. return isNaN(num) ? 0 : Math.floor(Math.round(num));
  103. },
  104. getArray: function (obj) {
  105. var i, arr = [], len = obj && obj.length || 0;
  106. for (i = 0; i < len; i++) {
  107. arr.push(obj[i]);
  108. }
  109. return arr;
  110. },
  111. getFileRelativePath: function (file) {
  112. /** @namespace file.relativePath */
  113. /** @namespace file.webkitRelativePath */
  114. return String(file.newPath || file.relativePath || file.webkitRelativePath || $h.getFileName(file) || null);
  115. },
  116. getFileId: function (file, generateFileId) {
  117. var relativePath = $h.getFileRelativePath(file);
  118. if (typeof generateFileId === 'function') {
  119. return generateFileId(file);
  120. }
  121. if (!file) {
  122. return null;
  123. }
  124. if (!relativePath) {
  125. return null;
  126. }
  127. return (file.size + '_' + encodeURIComponent(relativePath).replace(/%/g, '_'));
  128. },
  129. getFrameSelector: function (id, selector) {
  130. selector = selector || '';
  131. return '[id="' + id + '"]' + selector;
  132. },
  133. getZoomSelector: function (id, selector) {
  134. return $h.getFrameSelector('zoom-' + id, selector);
  135. },
  136. getFrameElement: function ($element, id, selector) {
  137. return $element.find($h.getFrameSelector(id, selector));
  138. },
  139. getZoomElement: function ($element, id, selector) {
  140. return $element.find($h.getZoomSelector(id, selector));
  141. },
  142. getElapsed: function (seconds) {
  143. var delta = seconds, out = '', result = {}, structure = {
  144. year: 31536000,
  145. month: 2592000,
  146. week: 604800, // uncomment row to ignore
  147. day: 86400, // feel free to add your own row
  148. hour: 3600,
  149. minute: 60,
  150. second: 1
  151. };
  152. $h.getObjectKeys(structure).forEach(function (key) {
  153. result[key] = Math.floor(delta / structure[key]);
  154. delta -= result[key] * structure[key];
  155. });
  156. $.each(result, function (key, value) {
  157. if (value > 0) {
  158. out += (out ? ' ' : '') + value + key.substring(0, 1);
  159. }
  160. });
  161. return out;
  162. },
  163. debounce: function (func, delay) {
  164. var inDebounce;
  165. return function () {
  166. var args = arguments, context = this;
  167. clearTimeout(inDebounce);
  168. inDebounce = setTimeout(function () {
  169. func.apply(context, args);
  170. }, delay);
  171. };
  172. },
  173. stopEvent: function (e) {
  174. e.stopPropagation();
  175. e.preventDefault();
  176. },
  177. getFileName: function (file) {
  178. /** @namespace file.fileName */
  179. return file ? (file.fileName || file.name || '') : ''; // some confusion in different versions of Firefox
  180. },
  181. createObjectURL: function (data) {
  182. if ($h.objUrl && $h.objUrl.createObjectURL && data) {
  183. return $h.objUrl.createObjectURL(data);
  184. }
  185. return '';
  186. },
  187. revokeObjectURL: function (data) {
  188. if ($h.objUrl && $h.objUrl.revokeObjectURL && data) {
  189. $h.objUrl.revokeObjectURL(data);
  190. }
  191. },
  192. compare: function (input, str, exact) {
  193. return input !== undefined && (exact ? input === str : input.match(str));
  194. },
  195. isIE: function (ver) {
  196. var div, status;
  197. // check for IE versions < 11
  198. if (navigator.appName !== 'Microsoft Internet Explorer') {
  199. return false;
  200. }
  201. if (ver === 10) {
  202. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  203. }
  204. div = document.createElement('div');
  205. div.innerHTML = '<!--[if IE ' + ver + ']> <i></i> <![endif]-->';
  206. status = div.getElementsByTagName('i').length;
  207. document.body.appendChild(div);
  208. div.parentNode.removeChild(div);
  209. return status;
  210. },
  211. canOrientImage: function ($el) {
  212. var $img = $(document.createElement('img')).css({width: '1px', height: '1px'}).insertAfter($el),
  213. flag = $img.css('image-orientation');
  214. $img.remove();
  215. return !!flag;
  216. },
  217. canAssignFilesToInput: function () {
  218. var input = document.createElement('input');
  219. try {
  220. input.type = 'file';
  221. input.files = null;
  222. return true;
  223. } catch (err) {
  224. return false;
  225. }
  226. },
  227. getDragDropFolders: function (items) {
  228. var i, item, len = items ? items.length : 0, folders = 0;
  229. if (len > 0 && items[0].webkitGetAsEntry()) {
  230. for (i = 0; i < len; i++) {
  231. item = items[i].webkitGetAsEntry();
  232. if (item && item.isDirectory) {
  233. folders++;
  234. }
  235. }
  236. }
  237. return folders;
  238. },
  239. initModal: function ($modal) {
  240. var $body = $('body');
  241. if ($body.length) {
  242. $modal.appendTo($body);
  243. }
  244. },
  245. isFunction: function (v) {
  246. return typeof v === 'function';
  247. },
  248. isEmpty: function (value, trim) {
  249. if (value === undefined || value === null || value === '') {
  250. return true;
  251. }
  252. if ($h.isString(value) && trim) {
  253. return $.trim(value) === '';
  254. }
  255. if ($h.isArray(value)) {
  256. return value.length === 0;
  257. }
  258. if ($.isPlainObject(value) && $.isEmptyObject(value)) {
  259. return true
  260. }
  261. return false;
  262. },
  263. isArray: function (a) {
  264. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  265. },
  266. isString: function (a) {
  267. return Object.prototype.toString.call(a) === '[object String]';
  268. },
  269. ifSet: function (needle, haystack, def) {
  270. def = def || '';
  271. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  272. },
  273. cleanArray: function (arr) {
  274. if (!(arr instanceof Array)) {
  275. arr = [];
  276. }
  277. return arr.filter(function (e) {
  278. return (e !== undefined && e !== null);
  279. });
  280. },
  281. spliceArray: function (arr, index, reverseOrder) {
  282. var i, j = 0, out = [], newArr;
  283. if (!(arr instanceof Array)) {
  284. return [];
  285. }
  286. newArr = $.extend(true, [], arr);
  287. if (reverseOrder) {
  288. newArr.reverse();
  289. }
  290. for (i = 0; i < newArr.length; i++) {
  291. if (i !== index) {
  292. out[j] = newArr[i];
  293. j++;
  294. }
  295. }
  296. if (reverseOrder) {
  297. out.reverse();
  298. }
  299. return out;
  300. },
  301. getNum: function (num, def) {
  302. def = def || 0;
  303. if (typeof num === 'number') {
  304. return num;
  305. }
  306. if (typeof num === 'string') {
  307. num = parseFloat(num);
  308. }
  309. return isNaN(num) ? def : num;
  310. },
  311. hasFileAPISupport: function () {
  312. return !!(window.File && window.FileReader);
  313. },
  314. hasDragDropSupport: function () {
  315. var div = document.createElement('div');
  316. /** @namespace div.draggable */
  317. /** @namespace div.ondragstart */
  318. /** @namespace div.ondrop */
  319. return !$h.isIE(9) &&
  320. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  321. },
  322. hasFileUploadSupport: function () {
  323. return $h.hasFileAPISupport() && window.FormData;
  324. },
  325. hasBlobSupport: function () {
  326. try {
  327. return !!window.Blob && Boolean(new Blob());
  328. } catch (e) {
  329. return false;
  330. }
  331. },
  332. hasArrayBufferViewSupport: function () {
  333. try {
  334. return new Blob([new Uint8Array(100)]).size === 100;
  335. } catch (e) {
  336. return false;
  337. }
  338. },
  339. hasResumableUploadSupport: function () {
  340. /** @namespace Blob.prototype.webkitSlice */
  341. /** @namespace Blob.prototype.mozSlice */
  342. return $h.hasFileUploadSupport() && $h.hasBlobSupport() && $h.hasArrayBufferViewSupport() &&
  343. (!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false);
  344. },
  345. dataURI2Blob: function (dataURI) {
  346. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder ||
  347. window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb,
  348. canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array;
  349. if (!canProceed) {
  350. return null;
  351. }
  352. if (dataURI.split(',')[0].indexOf('base64') >= 0) {
  353. byteStr = atob(dataURI.split(',')[1]);
  354. } else {
  355. byteStr = decodeURIComponent(dataURI.split(',')[1]);
  356. }
  357. arrayBuffer = new ArrayBuffer(byteStr.length);
  358. intArray = new Uint8Array(arrayBuffer);
  359. for (i = 0; i < byteStr.length; i += 1) {
  360. intArray[i] = byteStr.charCodeAt(i);
  361. }
  362. mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0];
  363. if (canBlob) {
  364. return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr});
  365. }
  366. bb = new BlobBuilder();
  367. bb.append(arrayBuffer);
  368. return bb.getBlob(mimeStr);
  369. },
  370. arrayBuffer2String: function (buffer) {
  371. if (window.TextDecoder) {
  372. return new TextDecoder('utf-8').decode(buffer);
  373. }
  374. var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3;
  375. len = array.length;
  376. while (i < len) {
  377. c = array[i++];
  378. switch (c >> 4) { // jshint ignore:line
  379. case 0:
  380. case 1:
  381. case 2:
  382. case 3:
  383. case 4:
  384. case 5:
  385. case 6:
  386. case 7:
  387. // 0xxxxxxx
  388. out += String.fromCharCode(c);
  389. break;
  390. case 12:
  391. case 13:
  392. // 110x xxxx 10xx xxxx
  393. char2 = array[i++];
  394. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line
  395. break;
  396. case 14:
  397. // 1110 xxxx 10xx xxxx 10xx xxxx
  398. char2 = array[i++];
  399. char3 = array[i++];
  400. out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line
  401. ((char2 & 0x3F) << 6) | // jshint ignore:line
  402. ((char3 & 0x3F) << 0)); // jshint ignore:line
  403. break;
  404. }
  405. }
  406. return out;
  407. },
  408. isHtml: function (str) {
  409. var a = document.createElement('div');
  410. a.innerHTML = str;
  411. for (var c = a.childNodes, i = c.length; i--;) {
  412. if (c[i].nodeType === 1) {
  413. return true;
  414. }
  415. }
  416. return false;
  417. },
  418. isSvg: function (str) {
  419. return str.match(/^\s*<\?xml/i) && (str.match(/<!DOCTYPE svg/i) || str.match(/<svg/i));
  420. },
  421. getMimeType: function (signature, contents, type) {
  422. switch (signature) {
  423. case 'ffd8ffe0':
  424. case 'ffd8ffe1':
  425. case 'ffd8ffe2':
  426. return 'image/jpeg';
  427. case '89504e47':
  428. return 'image/png';
  429. case '47494638':
  430. return 'image/gif';
  431. case '49492a00':
  432. return 'image/tiff';
  433. case '52494646':
  434. return 'image/webp';
  435. case '66747970':
  436. return 'video/3gp';
  437. case '4f676753':
  438. return 'video/ogg';
  439. case '1a45dfa3':
  440. return 'video/mkv';
  441. case '000001ba':
  442. case '000001b3':
  443. return 'video/mpeg';
  444. case '3026b275':
  445. return 'video/wmv';
  446. case '25504446':
  447. return 'application/pdf';
  448. case '25215053':
  449. return 'application/ps';
  450. case '504b0304':
  451. case '504b0506':
  452. case '504b0508':
  453. return 'application/zip';
  454. case '377abcaf':
  455. return 'application/7z';
  456. case '75737461':
  457. return 'application/tar';
  458. case '7801730d':
  459. return 'application/dmg';
  460. default:
  461. switch (signature.substring(0, 6)) {
  462. case '435753':
  463. return 'application/x-shockwave-flash';
  464. case '494433':
  465. return 'audio/mp3';
  466. case '425a68':
  467. return 'application/bzip';
  468. default:
  469. switch (signature.substring(0, 4)) {
  470. case '424d':
  471. return 'image/bmp';
  472. case 'fffb':
  473. return 'audio/mp3';
  474. case '4d5a':
  475. return 'application/exe';
  476. case '1f9d':
  477. case '1fa0':
  478. return 'application/zip';
  479. case '1f8b':
  480. return 'application/gzip';
  481. default:
  482. return contents && !contents.match(
  483. /[^\u0000-\u007f]/) ? 'application/text-plain' : type;
  484. }
  485. }
  486. }
  487. },
  488. addCss: function ($el, css) {
  489. $el.removeClass(css).addClass(css);
  490. },
  491. getElement: function (options, param, value) {
  492. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  493. },
  494. createElement: function (str, tag) {
  495. tag = tag || 'div';
  496. return $($.parseHTML('<' + tag + '>' + str + '</' + tag + '>'));
  497. },
  498. uniqId: function () {
  499. return (new Date().getTime() + Math.floor(Math.random() * Math.pow(10, 15))).toString(36);
  500. },
  501. cspBuffer: {
  502. CSP_ATTRIB: 'data-csp-01928735', // a randomly named temporary attribute to store the CSP elem id
  503. domElementsStyles: {},
  504. stash: function (htmlString) {
  505. var self = this, outerDom = $.parseHTML('<div>' + htmlString + '</div>'), $el = $(outerDom);
  506. $el.find('[style]').each(function (key, elem) {
  507. var $elem = $(elem), styleDeclaration = $elem[0].style, id = $h.uniqId(), styles = {};
  508. if (styleDeclaration && styleDeclaration.length) {
  509. $(styleDeclaration).each(function () {
  510. styles[this] = styleDeclaration[this];
  511. });
  512. self.domElementsStyles[id] = styles;
  513. $elem.removeAttr('style').attr(self.CSP_ATTRIB, id);
  514. }
  515. });
  516. $el.filter('*').removeAttr('style'); // make sure all style attr are removed
  517. var values = Object.values ? Object.values(outerDom) : Object.keys(outerDom).map(function (itm) {
  518. return outerDom[itm];
  519. });
  520. return values.flatMap(function (elem) {
  521. return elem.innerHTML;
  522. }).join('');
  523. },
  524. apply: function (domElement) {
  525. var self = this, $el = $(domElement);
  526. $el.find('[' + self.CSP_ATTRIB + ']').each(function (key, elem) {
  527. var $elem = $(elem), id = $elem.attr(self.CSP_ATTRIB), styles = self.domElementsStyles[id];
  528. if (styles) {
  529. $elem.css(styles);
  530. }
  531. $elem.removeAttr(self.CSP_ATTRIB);
  532. });
  533. self.domElementsStyles = {};
  534. }
  535. },
  536. setHtml: function ($elem, htmlString) {
  537. var buf = $h.cspBuffer;
  538. $elem.html(buf.stash(htmlString));
  539. buf.apply($elem);
  540. return $elem;
  541. },
  542. htmlEncode: function (str, undefVal) {
  543. if (str === undefined) {
  544. return undefVal || null;
  545. }
  546. return str.replace(/&/g, '&amp;')
  547. .replace(/</g, '&lt;')
  548. .replace(/>/g, '&gt;')
  549. .replace(/"/g, '&quot;')
  550. .replace(/'/g, '&apos;');
  551. },
  552. replaceTags: function (str, tags) {
  553. var out = str;
  554. if (!tags) {
  555. return out;
  556. }
  557. $.each(tags, function (key, value) {
  558. if (typeof value === 'function') {
  559. value = value();
  560. }
  561. out = out.split(key).join(value);
  562. });
  563. return out;
  564. },
  565. cleanMemory: function ($thumb) {
  566. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  567. $h.revokeObjectURL(data);
  568. },
  569. findFileName: function (filePath) {
  570. var sepIndex = filePath.lastIndexOf('/');
  571. if (sepIndex === -1) {
  572. sepIndex = filePath.lastIndexOf('\\');
  573. }
  574. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  575. },
  576. checkFullScreen: function () {
  577. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  578. document.msFullscreenElement;
  579. },
  580. toggleFullScreen: function (maximize) {
  581. var doc = document, de = doc.documentElement, isFullScreen = $h.checkFullScreen();
  582. if (de && maximize && !isFullScreen) {
  583. if (de.requestFullscreen) {
  584. de.requestFullscreen();
  585. } else {
  586. if (de.msRequestFullscreen) {
  587. de.msRequestFullscreen();
  588. } else {
  589. if (de.mozRequestFullScreen) {
  590. de.mozRequestFullScreen();
  591. } else {
  592. if (de.webkitRequestFullscreen) {
  593. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  594. }
  595. }
  596. }
  597. }
  598. } else {
  599. if (isFullScreen) {
  600. if (doc.exitFullscreen) {
  601. doc.exitFullscreen();
  602. } else {
  603. if (doc.msExitFullscreen) {
  604. doc.msExitFullscreen();
  605. } else {
  606. if (doc.mozCancelFullScreen) {
  607. doc.mozCancelFullScreen();
  608. } else {
  609. if (doc.webkitExitFullscreen) {
  610. doc.webkitExitFullscreen();
  611. }
  612. }
  613. }
  614. }
  615. }
  616. }
  617. },
  618. moveArray: function (arr, oldIndex, newIndex, reverseOrder) {
  619. var newArr = $.extend(true, [], arr);
  620. if (reverseOrder) {
  621. newArr.reverse();
  622. }
  623. if (newIndex >= newArr.length) {
  624. var k = newIndex - newArr.length;
  625. while ((k--) + 1) {
  626. newArr.push(undefined);
  627. }
  628. }
  629. newArr.splice(newIndex, 0, newArr.splice(oldIndex, 1)[0]);
  630. if (reverseOrder) {
  631. newArr.reverse();
  632. }
  633. return newArr;
  634. },
  635. closeButton: function (css) {
  636. css = ($h.isBs(5) ? 'btn-close' : 'close') + (css ? ' ' + css : '');
  637. return '<button type="button" class="' + css + '" aria-label="Close">\n' +
  638. ($h.isBs(5) ? '' : ' <span aria-hidden="true">&times;</span>\n') +
  639. '</button>';
  640. },
  641. getRotation: function (value) {
  642. switch (value) {
  643. case 2:
  644. return 'rotateY(180deg)';
  645. case 3:
  646. return 'rotate(180deg)';
  647. case 4:
  648. return 'rotate(180deg) rotateY(180deg)';
  649. case 5:
  650. return 'rotate(270deg) rotateY(180deg)';
  651. case 6:
  652. return 'rotate(90deg)';
  653. case 7:
  654. return 'rotate(90deg) rotateY(180deg)';
  655. case 8:
  656. return 'rotate(270deg)';
  657. default:
  658. return '';
  659. }
  660. },
  661. setTransform: function (el, val) {
  662. if (!el) {
  663. return;
  664. }
  665. el.style.transform = val;
  666. el.style.webkitTransform = val;
  667. el.style['-moz-transform'] = val;
  668. el.style['-ms-transform'] = val;
  669. el.style['-o-transform'] = val;
  670. },
  671. getObjectKeys: function (obj) {
  672. var keys = [];
  673. if (obj) {
  674. $.each(obj, function (key) {
  675. keys.push(key);
  676. });
  677. }
  678. return keys;
  679. },
  680. getObjectSize: function (obj) {
  681. return $h.getObjectKeys(obj).length;
  682. },
  683. /**
  684. * Small dependency injection for the task manager
  685. * https://gist.github.com/fearphage/4341799
  686. */
  687. whenAll: function (array) {
  688. var s = [].slice, resolveValues = arguments.length === 1 && $h.isArray(array) ? array : s.call(arguments),
  689. deferred = $.Deferred(), i, failed = 0, value, length = resolveValues.length,
  690. remaining = length, rejectContexts, rejectValues, resolveContexts, updateFunc;
  691. rejectContexts = rejectValues = resolveContexts = Array(length);
  692. updateFunc = function (index, contexts, values) {
  693. return function () {
  694. if (values !== resolveValues) {
  695. failed++;
  696. }
  697. deferred.notifyWith(contexts[index] = this, values[index] = s.call(arguments));
  698. if (!(--remaining)) {
  699. deferred[(!failed ? 'resolve' : 'reject') + 'With'](contexts, values);
  700. }
  701. };
  702. };
  703. for (i = 0; i < length; i++) {
  704. if ((value = resolveValues[i]) && $.isFunction(value.promise)) {
  705. value.promise()
  706. .done(updateFunc(i, resolveContexts, resolveValues))
  707. .fail(updateFunc(i, rejectContexts, rejectValues));
  708. } else {
  709. deferred.notifyWith(this, value);
  710. --remaining;
  711. }
  712. }
  713. if (!remaining) {
  714. deferred.resolveWith(resolveContexts, resolveValues);
  715. }
  716. return deferred.promise();
  717. }
  718. };
  719. FileInput = function (element, options) {
  720. var self = this;
  721. self.$element = $(element);
  722. self.$parent = self.$element.parent();
  723. if (!self._validate()) {
  724. return;
  725. }
  726. self.isPreviewable = $h.hasFileAPISupport();
  727. self.isIE9 = $h.isIE(9);
  728. self.isIE10 = $h.isIE(10);
  729. if (self.isPreviewable || self.isIE9) {
  730. self._init(options);
  731. self._listen();
  732. }
  733. self.$element.removeClass('file-loading');
  734. };
  735. FileInput.prototype = {
  736. constructor: FileInput,
  737. _cleanup: function () {
  738. var self = this;
  739. self.reader = null;
  740. self.clearFileStack();
  741. self.fileBatchCompleted = true;
  742. self.isError = false;
  743. self.isDuplicateError = false;
  744. self.isPersistentError = false;
  745. self.cancelling = false;
  746. self.paused = false;
  747. self.lastProgress = 0;
  748. self._initAjax();
  749. },
  750. _isAborted: function () {
  751. var self = this;
  752. return self.cancelling || self.paused;
  753. },
  754. _initAjax: function () {
  755. var self = this, tm = self.taskManager = {
  756. pool: {},
  757. addPool: function (id) {
  758. return (tm.pool[id] = new tm.TasksPool(id));
  759. },
  760. getPool: function (id) {
  761. return tm.pool[id];
  762. },
  763. addTask: function (id, logic) { // add standalone task directly from task manager
  764. return new tm.Task(id, logic);
  765. },
  766. TasksPool: function (id) {
  767. var tp = this;
  768. tp.id = id;
  769. tp.cancelled = false;
  770. tp.cancelledDeferrer = $.Deferred();
  771. tp.tasks = {};
  772. tp.addTask = function (id, logic) {
  773. return (tp.tasks[id] = new tm.Task(id, logic));
  774. };
  775. tp.size = function () {
  776. return $h.getObjectSize(tp.tasks);
  777. };
  778. tp.run = function (maxThreads) {
  779. var i = 0, failed = false, task, tasksList = $h.getObjectKeys(tp.tasks).map(function (key) {
  780. return tp.tasks[key];
  781. }), tasksDone = [], deferred = $.Deferred(), enqueue, callback;
  782. if (tp.cancelled) {
  783. tp.cancelledDeferrer.resolve();
  784. return deferred.reject();
  785. }
  786. // if run all at once
  787. if (!maxThreads) {
  788. var tasksDeferredList = $h.getObjectKeys(tp.tasks).map(function (key) {
  789. return tp.tasks[key].deferred;
  790. });
  791. // when all are done
  792. $h.whenAll(tasksDeferredList).done(function () {
  793. var argv = $h.getArray(arguments);
  794. if (!tp.cancelled) {
  795. deferred.resolve.apply(null, argv);
  796. tp.cancelledDeferrer.reject();
  797. } else {
  798. deferred.reject.apply(null, argv);
  799. tp.cancelledDeferrer.resolve();
  800. }
  801. }).fail(function () {
  802. var argv = $h.getArray(arguments);
  803. deferred.reject.apply(null, argv);
  804. if (!tp.cancelled) {
  805. tp.cancelledDeferrer.reject();
  806. } else {
  807. tp.cancelledDeferrer.resolve();
  808. }
  809. });
  810. // run all tasks
  811. $.each(tp.tasks, function (id) {
  812. task = tp.tasks[id];
  813. task.run();
  814. });
  815. return deferred;
  816. }
  817. enqueue = function (task) {
  818. $.when(task.deferred)
  819. .fail(function () {
  820. failed = true;
  821. callback.apply(null, arguments);
  822. })
  823. .always(callback);
  824. };
  825. callback = function () {
  826. var argv = $h.getArray(arguments);
  827. // notify a task just ended
  828. deferred.notify(argv);
  829. tasksDone.push(argv);
  830. if (tp.cancelled) {
  831. deferred.reject.apply(null, tasksDone);
  832. tp.cancelledDeferrer.resolve();
  833. return;
  834. }
  835. if (tasksDone.length === tp.size()) {
  836. if (failed) {
  837. deferred.reject.apply(null, tasksDone);
  838. } else {
  839. deferred.resolve.apply(null, tasksDone);
  840. }
  841. }
  842. // if there are any tasks remaining
  843. if (tasksList.length) {
  844. task = tasksList.shift();
  845. enqueue(task);
  846. task.run();
  847. }
  848. };
  849. // run the first "maxThreads" tasks
  850. while (tasksList.length && i++ < maxThreads) {
  851. task = tasksList.shift();
  852. enqueue(task);
  853. task.run();
  854. }
  855. return deferred;
  856. };
  857. tp.cancel = function () {
  858. tp.cancelled = true;
  859. return tp.cancelledDeferrer;
  860. };
  861. },
  862. Task: function (id, logic) {
  863. var tk = this;
  864. tk.id = id;
  865. tk.deferred = $.Deferred();
  866. tk.logic = logic;
  867. tk.context = null;
  868. tk.run = function () {
  869. var argv = $h.getArray(arguments);
  870. argv.unshift(tk.deferred); // add deferrer as first argument
  871. logic.apply(tk.context, argv); // run task
  872. return tk.deferred; // return deferrer
  873. };
  874. tk.runWithContext = function (context) {
  875. tk.context = context;
  876. return tk.run();
  877. };
  878. }
  879. };
  880. self.ajaxQueue = [];
  881. self.ajaxRequests = [];
  882. self.ajaxAborted = false;
  883. },
  884. _init: function (options, refreshMode) {
  885. var self = this, f, $el = self.$element, $cont, t, tmp;
  886. self.options = options;
  887. self.canOrientImage = $h.canOrientImage($el);
  888. $.each(options, function (key, value) {
  889. switch (key) {
  890. case 'minFileCount':
  891. case 'maxFileCount':
  892. case 'maxTotalFileCount':
  893. case 'minFileSize':
  894. case 'maxFileSize':
  895. case 'maxFilePreviewSize':
  896. case 'resizeQuality':
  897. case 'resizeIfSizeMoreThan':
  898. case 'progressUploadThreshold':
  899. case 'initialPreviewCount':
  900. case 'zoomModalHeight':
  901. case 'minImageHeight':
  902. case 'maxImageHeight':
  903. case 'minImageWidth':
  904. case 'maxImageWidth':
  905. case 'bytesToKB':
  906. self[key] = $h.getNum(value);
  907. break;
  908. default:
  909. self[key] = value;
  910. break;
  911. }
  912. });
  913. if (!self.bytesToKB || self.bytesToKB <= 0) {
  914. self.bytesToKB = 1024;
  915. }
  916. if (self.errorCloseButton === undefined) {
  917. self.errorCloseButton = $h.closeButton('kv-error-close' + ($h.isBs(5) ? ' float-end' : ''));
  918. }
  919. if (self.maxTotalFileCount > 0 && self.maxTotalFileCount < self.maxFileCount) {
  920. self.maxTotalFileCount = self.maxFileCount;
  921. }
  922. if (self.rtl) { // swap buttons for rtl
  923. tmp = self.previewZoomButtonIcons.prev;
  924. self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next;
  925. self.previewZoomButtonIcons.next = tmp;
  926. }
  927. // validate chunk threads to not exceed maxAjaxThreads
  928. if (!isNaN(self.maxAjaxThreads) && self.maxAjaxThreads < self.resumableUploadOptions.maxThreads) {
  929. self.resumableUploadOptions.maxThreads = self.maxAjaxThreads;
  930. }
  931. self._initFileManager();
  932. if (typeof self.autoOrientImage === 'function') {
  933. self.autoOrientImage = self.autoOrientImage();
  934. }
  935. if (typeof self.autoOrientImageInitial === 'function') {
  936. self.autoOrientImageInitial = self.autoOrientImageInitial();
  937. }
  938. if (!refreshMode) {
  939. self._cleanup();
  940. }
  941. self.duplicateErrors = [];
  942. self.$form = $el.closest('form');
  943. self._initTemplateDefaults();
  944. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  945. t = self._getLayoutTemplate('progress');
  946. self.progressTemplate = t.replace('{class}', self.progressClass);
  947. self.progressInfoTemplate = t.replace('{class}', self.progressInfoClass);
  948. self.progressPauseTemplate = t.replace('{class}', self.progressPauseClass);
  949. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  950. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  951. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  952. if (self.isDisabled) {
  953. $el.attr('disabled', true);
  954. }
  955. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  956. (self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  957. self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  958. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  959. if (!self.isAjaxUpload) {
  960. self.dropZoneEnabled = self.dropZoneEnabled && $h.canAssignFilesToInput();
  961. }
  962. self.slug = typeof options.slugCallback === 'function' ? options.slugCallback : self._slugDefault;
  963. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  964. self.captionTemplate = self._getLayoutTemplate('caption');
  965. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  966. if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  967. self.imageCanvas = document.createElement('canvas');
  968. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  969. }
  970. if ($h.isEmpty($el.attr('id'))) {
  971. $el.attr('id', $h.uniqId());
  972. }
  973. self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
  974. if (self.$container === undefined) {
  975. self.$container = self._createContainer();
  976. } else {
  977. self._refreshContainer();
  978. }
  979. $cont = self.$container;
  980. self.$dropZone = $cont.find('.file-drop-zone');
  981. self.$progress = $cont.find('.kv-upload-progress');
  982. self.$btnUpload = $cont.find('.fileinput-upload');
  983. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
  984. self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
  985. if (!$h.isEmpty(self.msgPlaceholder)) {
  986. f = $el.attr('multiple') ? self.filePlural : self.fileSingle;
  987. self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f));
  988. }
  989. self.$captionIcon = self.$captionContainer.find('.file-caption-icon');
  990. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
  991. self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
  992. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
  993. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  994. self.$previewContainer.find('.kv-fileinput-error'));
  995. self._validateDisabled();
  996. if (!$h.isEmpty(self.msgErrorClass)) {
  997. $h.addCss(self.$errorContainer, self.msgErrorClass);
  998. }
  999. if (!refreshMode) {
  1000. self._resetErrors();
  1001. self.$errorContainer.hide();
  1002. self.previewInitId = 'thumb-' + $el.attr('id');
  1003. self._initPreviewCache();
  1004. self._initPreview(true);
  1005. self._initPreviewActions();
  1006. if (self.$parent.hasClass('file-loading')) {
  1007. self.$container.insertBefore(self.$parent);
  1008. self.$parent.remove();
  1009. }
  1010. } else {
  1011. if (!self._errorsExist()) {
  1012. self.$errorContainer.hide();
  1013. }
  1014. }
  1015. self._setFileDropZoneTitle();
  1016. if ($el.attr('disabled')) {
  1017. self.disable();
  1018. }
  1019. self._initZoom();
  1020. if (self.hideThumbnailContent) {
  1021. $h.addCss(self.$preview, 'hide-content');
  1022. }
  1023. },
  1024. _initFileManager: function () {
  1025. var self = this;
  1026. self.uploadStartTime = $h.now();
  1027. self.fileManager = {
  1028. stack: {},
  1029. filesProcessed: [],
  1030. errors: [],
  1031. loadedImages: {},
  1032. totalImages: 0,
  1033. totalFiles: null,
  1034. totalSize: null,
  1035. uploadedSize: 0,
  1036. stats: {},
  1037. bpsLog: [],
  1038. bps: 0,
  1039. initStats: function (id) {
  1040. var data = {started: $h.now()};
  1041. if (id) {
  1042. self.fileManager.stats[id] = data;
  1043. } else {
  1044. self.fileManager.stats = data;
  1045. }
  1046. },
  1047. getUploadStats: function (id, loaded, total) {
  1048. var fm = self.fileManager,
  1049. started = id ? fm.stats[id] && fm.stats[id].started || $h.now() : self.uploadStartTime,
  1050. elapsed = ($h.now() - started) / 1000, bps = Math.ceil(elapsed ? loaded / elapsed : 0),
  1051. pendingBytes = total - loaded, out, delay = fm.bpsLog.length ? self.bitrateUpdateDelay : 0;
  1052. setTimeout(function () {
  1053. var i, j = 0, n = 0, len, beg;
  1054. fm.bpsLog.push(bps);
  1055. fm.bpsLog.sort(function (a, b) {
  1056. return a - b;
  1057. });
  1058. len = fm.bpsLog.length;
  1059. beg = len > 10 ? len - 10 : Math.ceil(len / 2);
  1060. for (i = len; i > beg; i--) {
  1061. n = parseFloat(fm.bpsLog[i]);
  1062. j++;
  1063. }
  1064. fm.bps = (j > 0 ? n / j : 0) * 64;
  1065. }, delay);
  1066. out = {
  1067. fileId: id,
  1068. started: started,
  1069. elapsed: elapsed,
  1070. loaded: loaded,
  1071. total: total,
  1072. bps: fm.bps,
  1073. bitrate: self._getSize(fm.bps, self.bitRateUnits),
  1074. pendingBytes: pendingBytes
  1075. };
  1076. if (id) {
  1077. fm.stats[id] = out;
  1078. } else {
  1079. fm.stats = out;
  1080. }
  1081. return out;
  1082. },
  1083. exists: function (id) {
  1084. return $.inArray(id, self.fileManager.getIdList()) !== -1;
  1085. },
  1086. count: function () {
  1087. return self.fileManager.getIdList().length;
  1088. },
  1089. total: function () {
  1090. var fm = self.fileManager;
  1091. if (!fm.totalFiles) {
  1092. fm.totalFiles = fm.count();
  1093. }
  1094. return fm.totalFiles;
  1095. },
  1096. getTotalSize: function () {
  1097. var fm = self.fileManager;
  1098. if (fm.totalSize) {
  1099. return fm.totalSize;
  1100. }
  1101. fm.totalSize = 0;
  1102. $.each(self.getFileStack(), function (id, f) {
  1103. var size = parseFloat(f.size);
  1104. fm.totalSize += isNaN(size) ? 0 : size;
  1105. });
  1106. return fm.totalSize;
  1107. },
  1108. add: function (file, id) {
  1109. if (!id) {
  1110. id = self.fileManager.getId(file);
  1111. }
  1112. if (!id) {
  1113. return;
  1114. }
  1115. self.fileManager.stack[id] = {
  1116. file: file,
  1117. name: $h.getFileName(file),
  1118. relativePath: $h.getFileRelativePath(file),
  1119. size: file.size,
  1120. nameFmt: self._getFileName(file, ''),
  1121. sizeFmt: self._getSize(file.size)
  1122. };
  1123. },
  1124. remove: function ($thumb) {
  1125. var id = self._getThumbFileId($thumb);
  1126. self.fileManager.removeFile(id);
  1127. },
  1128. removeFile: function (id) {
  1129. var fm = self.fileManager;
  1130. if (!id) {
  1131. return;
  1132. }
  1133. delete fm.stack[id];
  1134. delete fm.loadedImages[id];
  1135. },
  1136. move: function (idFrom, idTo) {
  1137. var result = {}, stack = self.fileManager.stack;
  1138. if (!idFrom && !idTo || idFrom === idTo) {
  1139. return;
  1140. }
  1141. $.each(stack, function (k, v) {
  1142. if (k !== idFrom) {
  1143. result[k] = v;
  1144. }
  1145. if (k === idTo) {
  1146. result[idFrom] = stack[idFrom];
  1147. }
  1148. });
  1149. self.fileManager.stack = result;
  1150. },
  1151. list: function () {
  1152. var files = [];
  1153. $.each(self.getFileStack(), function (k, v) {
  1154. if (v && v.file) {
  1155. files.push(v.file);
  1156. }
  1157. });
  1158. return files;
  1159. },
  1160. isPending: function (id) {
  1161. return $.inArray(id, self.fileManager.filesProcessed) === -1 && self.fileManager.exists(id);
  1162. },
  1163. isProcessed: function () {
  1164. var filesProcessed = true, fm = self.fileManager;
  1165. $.each(self.getFileStack(), function (id) {
  1166. if (fm.isPending(id)) {
  1167. filesProcessed = false;
  1168. }
  1169. });
  1170. return filesProcessed;
  1171. },
  1172. clear: function () {
  1173. var fm = self.fileManager;
  1174. self.isDuplicateError = false;
  1175. self.isPersistentError = false;
  1176. fm.totalFiles = null;
  1177. fm.totalSize = null;
  1178. fm.uploadedSize = 0;
  1179. fm.stack = {};
  1180. fm.errors = [];
  1181. fm.filesProcessed = [];
  1182. fm.stats = {};
  1183. fm.bpsLog = [];
  1184. fm.bps = 0;
  1185. fm.clearImages();
  1186. },
  1187. clearImages: function () {
  1188. self.fileManager.loadedImages = {};
  1189. self.fileManager.totalImages = 0;
  1190. },
  1191. addImage: function (id, config) {
  1192. self.fileManager.loadedImages[id] = config;
  1193. },
  1194. removeImage: function (id) {
  1195. delete self.fileManager.loadedImages[id];
  1196. },
  1197. getImageIdList: function () {
  1198. return $h.getObjectKeys(self.fileManager.loadedImages);
  1199. },
  1200. getImageCount: function () {
  1201. return self.fileManager.getImageIdList().length;
  1202. },
  1203. getId: function (file) {
  1204. return self._getFileId(file);
  1205. },
  1206. getIndex: function (id) {
  1207. return self.fileManager.getIdList().indexOf(id);
  1208. },
  1209. getThumb: function (id) {
  1210. var $thumb = null;
  1211. self._getThumbs().each(function () {
  1212. var $t = $(this);
  1213. if (self._getThumbFileId($t) === id) {
  1214. $thumb = $t;
  1215. }
  1216. });
  1217. return $thumb;
  1218. },
  1219. getThumbIndex: function ($thumb) {
  1220. var id = self._getThumbFileId($thumb);
  1221. return self.fileManager.getIndex(id);
  1222. },
  1223. getIdList: function () {
  1224. return $h.getObjectKeys(self.fileManager.stack);
  1225. },
  1226. getFile: function (id) {
  1227. return self.fileManager.stack[id] || null;
  1228. },
  1229. getFileName: function (id, fmt) {
  1230. var file = self.fileManager.getFile(id);
  1231. if (!file) {
  1232. return '';
  1233. }
  1234. return fmt ? (file.nameFmt || '') : file.name || '';
  1235. },
  1236. getFirstFile: function () {
  1237. var ids = self.fileManager.getIdList(), id = ids && ids.length ? ids[0] : null;
  1238. return self.fileManager.getFile(id);
  1239. },
  1240. setFile: function (id, file) {
  1241. if (self.fileManager.getFile(id)) {
  1242. self.fileManager.stack[id].file = file;
  1243. } else {
  1244. self.fileManager.add(file, id);
  1245. }
  1246. },
  1247. setProcessed: function (id) {
  1248. self.fileManager.filesProcessed.push(id);
  1249. },
  1250. getProgress: function () {
  1251. var total = self.fileManager.total(), filesProcessed = self.fileManager.filesProcessed.length;
  1252. if (!total) {
  1253. return 0;
  1254. }
  1255. return Math.ceil(filesProcessed / total * 100);
  1256. },
  1257. setProgress: function (id, pct) {
  1258. var f = self.fileManager.getFile(id);
  1259. if (!isNaN(pct) && f) {
  1260. f.progress = pct;
  1261. }
  1262. }
  1263. };
  1264. },
  1265. _setUploadData: function (fd, config) {
  1266. var self = this;
  1267. $.each(config, function (key, value) {
  1268. var param = self.uploadParamNames[key] || key;
  1269. if ($h.isArray(value)) {
  1270. fd.append(param, value[0], value[1]);
  1271. } else {
  1272. fd.append(param, value);
  1273. }
  1274. });
  1275. },
  1276. _initResumableUpload: function () {
  1277. var self = this, opts = self.resumableUploadOptions, logs = $h.logMessages, rm, fm = self.fileManager;
  1278. if (!self.enableResumableUpload) {
  1279. return;
  1280. }
  1281. if (opts.fallback !== false && typeof opts.fallback !== 'function') {
  1282. opts.fallback = function (s) {
  1283. s._log(logs.noResumableSupport);
  1284. s.enableResumableUpload = false;
  1285. };
  1286. }
  1287. if (!$h.hasResumableUploadSupport() && opts.fallback !== false) {
  1288. opts.fallback(self);
  1289. return;
  1290. }
  1291. if (!self.uploadUrl && self.enableResumableUpload) {
  1292. self._log(logs.noUploadUrl);
  1293. self.enableResumableUpload = false;
  1294. return;
  1295. }
  1296. opts.chunkSize = parseFloat(opts.chunkSize);
  1297. if (opts.chunkSize <= 0 || isNaN(opts.chunkSize)) {
  1298. self._log(logs.invalidChunkSize, {chunkSize: opts.chunkSize});
  1299. self.enableResumableUpload = false;
  1300. return;
  1301. }
  1302. rm = self.resumableManager = {
  1303. init: function (id, f, index) {
  1304. rm.logs = [];
  1305. rm.stack = [];
  1306. rm.error = '';
  1307. rm.id = id;
  1308. rm.file = f.file;
  1309. rm.fileName = f.name;
  1310. rm.fileIndex = index;
  1311. rm.completed = false;
  1312. rm.lastProgress = 0;
  1313. if (self.showPreview) {
  1314. rm.$thumb = fm.getThumb(id) || null;
  1315. rm.$progress = rm.$btnDelete = null;
  1316. if (rm.$thumb && rm.$thumb.length) {
  1317. rm.$progress = rm.$thumb.find('.file-thumb-progress');
  1318. rm.$btnDelete = rm.$thumb.find('.kv-file-remove');
  1319. }
  1320. }
  1321. rm.chunkSize = opts.chunkSize * self.bytesToKB;
  1322. rm.chunkCount = rm.getTotalChunks();
  1323. },
  1324. setAjaxError: function (jqXHR, textStatus, errorThrown, isTest) {
  1325. if (jqXHR.responseJSON && jqXHR.responseJSON.error) {
  1326. errorThrown = jqXHR.responseJSON.error.toString();
  1327. }
  1328. if (!isTest) {
  1329. rm.error = errorThrown;
  1330. }
  1331. if (opts.showErrorLog) {
  1332. self._log(logs.ajaxError, {
  1333. status: jqXHR.status,
  1334. error: errorThrown,
  1335. text: jqXHR.responseText || ''
  1336. });
  1337. }
  1338. },
  1339. reset: function () {
  1340. rm.stack = [];
  1341. rm.chunksProcessed = {};
  1342. },
  1343. setProcessed: function (status) {
  1344. var id = rm.id, msg, $thumb = rm.$thumb, $prog = rm.$progress, hasThumb = $thumb && $thumb.length,
  1345. params = {id: hasThumb ? $thumb.attr('id') : '', index: fm.getIndex(id), fileId: id}, tokens,
  1346. skipErrorsAndProceed = self.resumableUploadOptions.skipErrorsAndProceed;
  1347. rm.completed = true;
  1348. rm.lastProgress = 0;
  1349. if (hasThumb) {
  1350. $thumb.removeClass('file-uploading');
  1351. }
  1352. if (status === 'success') {
  1353. fm.uploadedSize += rm.file.size;
  1354. if (self.showPreview) {
  1355. self._setProgress(101, $prog);
  1356. self._setThumbStatus($thumb, 'Success');
  1357. self._initUploadSuccess(rm.chunksProcessed[id].data, $thumb);
  1358. }
  1359. fm.removeFile(id);
  1360. delete rm.chunksProcessed[id];
  1361. self._raise('fileuploaded', [params.id, params.index, params.fileId]);
  1362. if (fm.isProcessed()) {
  1363. self._setProgress(101);
  1364. }
  1365. } else {
  1366. if (status !== 'cancel') {
  1367. if (self.showPreview) {
  1368. self._setThumbStatus($thumb, 'Error');
  1369. self._setPreviewError($thumb, true);
  1370. self._setProgress(101, $prog, self.msgProgressError);
  1371. self._setProgress(101, self.$progress, self.msgProgressError);
  1372. self.cancelling = !skipErrorsAndProceed;
  1373. }
  1374. if (!self.$errorContainer.find('li[data-file-id="' + params.fileId + '"]').length) {
  1375. tokens = {file: rm.fileName, max: opts.maxRetries, error: rm.error};
  1376. msg = self.msgResumableUploadRetriesExceeded.setTokens(tokens);
  1377. $.extend(params, tokens);
  1378. self._showFileError(msg, params, 'filemaxretries');
  1379. if (skipErrorsAndProceed) {
  1380. fm.removeFile(id);
  1381. delete rm.chunksProcessed[id];
  1382. if (fm.isProcessed()) {
  1383. self._setProgress(101);
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. if (fm.isProcessed()) {
  1390. rm.reset();
  1391. }
  1392. },
  1393. check: function () {
  1394. var status = true;
  1395. $.each(rm.logs, function (index, value) {
  1396. if (!value) {
  1397. status = false;
  1398. return false;
  1399. }
  1400. });
  1401. },
  1402. processedResumables: function () {
  1403. var logs = rm.logs, i, count = 0;
  1404. if (!logs || !logs.length) {
  1405. return 0;
  1406. }
  1407. for (i = 0; i < logs.length; i++) {
  1408. if (logs[i] === true) {
  1409. count++;
  1410. }
  1411. }
  1412. return count;
  1413. },
  1414. getUploadedSize: function () {
  1415. var size = rm.processedResumables() * rm.chunkSize;
  1416. return size > rm.file.size ? rm.file.size : size;
  1417. },
  1418. getTotalChunks: function () {
  1419. var chunkSize = parseFloat(rm.chunkSize);
  1420. if (!isNaN(chunkSize) && chunkSize > 0) {
  1421. return Math.ceil(rm.file.size / chunkSize);
  1422. }
  1423. return 0;
  1424. },
  1425. getProgress: function () {
  1426. var chunksProcessed = rm.processedResumables(), total = rm.chunkCount;
  1427. if (total === 0) {
  1428. return 0;
  1429. }
  1430. return Math.ceil(chunksProcessed / total * 100);
  1431. },
  1432. checkAborted: function (intervalId) {
  1433. if (self._isAborted()) {
  1434. clearInterval(intervalId);
  1435. self.unlock();
  1436. }
  1437. },
  1438. upload: function () {
  1439. var ids = fm.getIdList(), flag = 'new', intervalId;
  1440. intervalId = setInterval(function () {
  1441. var id;
  1442. rm.checkAborted(intervalId);
  1443. if (flag === 'new') {
  1444. self.lock();
  1445. flag = 'processing';
  1446. id = ids.shift();
  1447. fm.initStats(id);
  1448. if (fm.stack[id]) {
  1449. rm.init(id, fm.stack[id], fm.getIndex(id));
  1450. rm.processUpload();
  1451. }
  1452. }
  1453. if (!fm.isPending(id) && rm.completed) {
  1454. flag = 'new';
  1455. }
  1456. if (fm.isProcessed()) {
  1457. var $initThumbs = self.$preview.find('.file-preview-initial');
  1458. if ($initThumbs.length) {
  1459. $h.addCss($initThumbs, $h.SORT_CSS);
  1460. self._initSortable();
  1461. }
  1462. clearInterval(intervalId);
  1463. self._clearFileInput();
  1464. self.unlock();
  1465. setTimeout(function () {
  1466. var data = self.previewCache.data;
  1467. if (data) {
  1468. self.initialPreview = data.content;
  1469. self.initialPreviewConfig = data.config;
  1470. self.initialPreviewThumbTags = data.tags;
  1471. }
  1472. self._raise('filebatchuploadcomplete', [
  1473. self.initialPreview,
  1474. self.initialPreviewConfig,
  1475. self.initialPreviewThumbTags,
  1476. self._getExtraData()
  1477. ]);
  1478. }, self.processDelay);
  1479. }
  1480. }, self.processDelay);
  1481. },
  1482. uploadResumable: function () {
  1483. var i, pool, tm = self.taskManager, total = rm.chunkCount;
  1484. pool = tm.addPool(rm.id);
  1485. for (i = 0; i < total; i++) {
  1486. rm.logs[i] = !!(rm.chunksProcessed[rm.id] && rm.chunksProcessed[rm.id][i]);
  1487. if (!rm.logs[i]) {
  1488. rm.pushAjax(i, 0);
  1489. }
  1490. }
  1491. pool.run(opts.maxThreads)
  1492. .done(function () {
  1493. rm.setProcessed('success');
  1494. })
  1495. .fail(function () {
  1496. rm.setProcessed(pool.cancelled ? 'cancel' : 'error');
  1497. });
  1498. },
  1499. processUpload: function () {
  1500. var fd, f, id = rm.id, fnBefore, fnSuccess, fnError, fnComplete, outData;
  1501. if (!opts.testUrl) {
  1502. rm.uploadResumable();
  1503. return;
  1504. }
  1505. fd = new FormData();
  1506. f = fm.stack[id];
  1507. self._setUploadData(fd, {
  1508. fileId: id,
  1509. fileName: f.fileName,
  1510. fileSize: f.size,
  1511. fileRelativePath: f.relativePath,
  1512. chunkSize: rm.chunkSize,
  1513. chunkCount: rm.chunkCount
  1514. });
  1515. fnBefore = function (jqXHR) {
  1516. outData = self._getOutData(fd, jqXHR);
  1517. self._raise('filetestbeforesend', [id, fm, rm, outData]);
  1518. };
  1519. fnSuccess = function (data, textStatus, jqXHR) {
  1520. outData = self._getOutData(fd, jqXHR, data);
  1521. var pNames = self.uploadParamNames, chunksUploaded = pNames.chunksUploaded || 'chunksUploaded',
  1522. params = [id, fm, rm, outData];
  1523. if (!data[chunksUploaded] || !$h.isArray(data[chunksUploaded])) {
  1524. self._raise('filetesterror', params);
  1525. } else {
  1526. if (!rm.chunksProcessed[id]) {
  1527. rm.chunksProcessed[id] = {};
  1528. }
  1529. $.each(data[chunksUploaded], function (key, index) {
  1530. rm.logs[index] = true;
  1531. rm.chunksProcessed[id][index] = true;
  1532. });
  1533. rm.chunksProcessed[id].data = data;
  1534. self._raise('filetestsuccess', params);
  1535. }
  1536. rm.uploadResumable();
  1537. };
  1538. fnError = function (jqXHR, textStatus, errorThrown) {
  1539. outData = self._getOutData(fd, jqXHR);
  1540. self._raise('filetestajaxerror', [id, fm, rm, outData]);
  1541. rm.setAjaxError(jqXHR, textStatus, errorThrown, true);
  1542. rm.uploadResumable();
  1543. };
  1544. fnComplete = function () {
  1545. self._raise('filetestcomplete', [id, fm, rm, self._getOutData(fd)]);
  1546. };
  1547. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex, opts.testUrl);
  1548. },
  1549. pushAjax: function (index, retry) {
  1550. var tm = self.taskManager, pool = tm.getPool(rm.id);
  1551. pool.addTask(pool.size() + 1, function (deferrer) {
  1552. // use fifo chunk stack
  1553. var arr = rm.stack.shift(), index;
  1554. index = arr[0];
  1555. if (!rm.chunksProcessed[rm.id] || !rm.chunksProcessed[rm.id][index]) {
  1556. rm.sendAjax(index, arr[1], deferrer);
  1557. } else {
  1558. self._log(logs.chunkQueueError, {index: index});
  1559. }
  1560. });
  1561. rm.stack.push([index, retry]);
  1562. },
  1563. sendAjax: function (index, retry, deferrer) {
  1564. var f, chunkSize = rm.chunkSize, id = rm.id, file = rm.file, $thumb = rm.$thumb,
  1565. msgs = $h.logMessages, $btnDelete = rm.$btnDelete, logError = function (msg, tokens) {
  1566. if (tokens) {
  1567. msg = msg.setTokens(tokens);
  1568. }
  1569. msg = msgs.resumableRequestError.setTokens({msg: msg});
  1570. self._log(msg);
  1571. deferrer.reject(msg);
  1572. };
  1573. if (rm.chunksProcessed[id] && rm.chunksProcessed[id][index]) {
  1574. return;
  1575. }
  1576. if (retry > opts.maxRetries) {
  1577. logError(msgs.resumableMaxRetriesReached, {n: opts.maxRetries});
  1578. rm.setProcessed('error');
  1579. return;
  1580. }
  1581. var fd, outData, fnBefore, fnSuccess, fnError, fnComplete, slice = file.slice ? 'slice' :
  1582. (file.mozSlice ? 'mozSlice' : (file.webkitSlice ? 'webkitSlice' : 'slice')),
  1583. blob = file[slice](chunkSize * index, chunkSize * (index + 1));
  1584. fd = new FormData();
  1585. f = fm.stack[id];
  1586. self._setUploadData(fd, {
  1587. chunkCount: rm.chunkCount,
  1588. chunkIndex: index,
  1589. chunkSize: chunkSize,
  1590. chunkSizeStart: chunkSize * index,
  1591. fileBlob: [blob, rm.fileName],
  1592. fileId: id,
  1593. fileName: rm.fileName,
  1594. fileRelativePath: f.relativePath,
  1595. fileSize: file.size,
  1596. retryCount: retry
  1597. });
  1598. if (rm.$progress && rm.$progress.length) {
  1599. rm.$progress.show();
  1600. }
  1601. fnBefore = function (jqXHR) {
  1602. outData = self._getOutData(fd, jqXHR);
  1603. if (self.showPreview) {
  1604. if (!$thumb.hasClass('file-preview-success')) {
  1605. self._setThumbStatus($thumb, 'Loading');
  1606. $h.addCss($thumb, 'file-uploading');
  1607. }
  1608. $btnDelete.attr('disabled', true);
  1609. }
  1610. self._raise('filechunkbeforesend', [id, index, retry, fm, rm, outData]);
  1611. };
  1612. fnSuccess = function (data, textStatus, jqXHR) {
  1613. if (self._isAborted()) {
  1614. logError(msgs.resumableAborting);
  1615. return;
  1616. }
  1617. outData = self._getOutData(fd, jqXHR, data);
  1618. var paramNames = self.uploadParamNames, chunkIndex = paramNames.chunkIndex || 'chunkIndex',
  1619. params = [id, index, retry, fm, rm, outData];
  1620. if (data.error) {
  1621. if (opts.showErrorLog) {
  1622. self._log(logs.retryStatus, {
  1623. retry: retry + 1,
  1624. filename: rm.fileName,
  1625. chunk: index
  1626. });
  1627. }
  1628. self._raise('filechunkerror', params);
  1629. rm.pushAjax(index, retry + 1);
  1630. rm.error = data.error;
  1631. logError(data.error);
  1632. } else {
  1633. rm.logs[data[chunkIndex]] = true;
  1634. if (!rm.chunksProcessed[id]) {
  1635. rm.chunksProcessed[id] = {};
  1636. }
  1637. rm.chunksProcessed[id][data[chunkIndex]] = true;
  1638. rm.chunksProcessed[id].data = data;
  1639. deferrer.resolve.call(null, data);
  1640. self._raise('filechunksuccess', params);
  1641. rm.check();
  1642. }
  1643. };
  1644. fnError = function (jqXHR, textStatus, errorThrown) {
  1645. if (self._isAborted()) {
  1646. logError(msgs.resumableAborting);
  1647. return;
  1648. }
  1649. outData = self._getOutData(fd, jqXHR);
  1650. rm.setAjaxError(jqXHR, textStatus, errorThrown);
  1651. self._raise('filechunkajaxerror', [id, index, retry, fm, rm, outData]);
  1652. rm.pushAjax(index, retry + 1); // push another task
  1653. logError(msgs.resumableRetryError, {n: retry - 1}); // resolve the current task
  1654. };
  1655. fnComplete = function () {
  1656. if (!self._isAborted()) {
  1657. self._raise('filechunkcomplete', [id, index, retry, fm, rm, self._getOutData(fd)]);
  1658. }
  1659. };
  1660. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex);
  1661. }
  1662. };
  1663. rm.reset();
  1664. },
  1665. _initTemplateDefaults: function () {
  1666. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  1667. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload,
  1668. tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage,
  1669. tText, tOffice, tGdocs, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tStyle, tZoomCache, vDefaultDim,
  1670. tStats, tModalLabel, tDescClose, renderObject = function (type, mime) {
  1671. return '<object class="kv-preview-data file-preview-' + type + '" title="{caption}" ' +
  1672. 'data="{data}" type="' + mime + '"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  1673. }, defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss();
  1674. tMain1 = '{preview}\n' +
  1675. '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n' +
  1676. '<div class="file-caption {class}">\n' +
  1677. ' <div class="input-group {inputGroupClass}">\n' +
  1678. ' {caption}\n<span class="file-caption-icon"></span>\n' +
  1679. ($h.isBs(5) ? '' : '<div class="input-group-btn input-group-append">\n') +
  1680. ' {remove}\n' +
  1681. ' {cancel}\n' +
  1682. ' {pause}\n' +
  1683. ' {upload}\n' +
  1684. ' {browse}\n' +
  1685. ($h.isBs(5) ? '' : ' </div>\n') +
  1686. ' </div>'
  1687. '</div>';
  1688. tMain2 = '{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n' +
  1689. '<span class="{class}">{remove}\n{cancel}\n{upload}\n{browse}\n</span>';
  1690. tPreview = '<div class="file-preview {class}">\n' +
  1691. ' {close}' +
  1692. ' <div class="{dropClass} clearfix">\n' +
  1693. ' <div class="file-preview-thumbnails clearfix">\n' +
  1694. ' </div>\n' +
  1695. ' <div class="file-preview-status text-center text-success"></div>\n' +
  1696. ' <div class="kv-fileinput-error"></div>\n' +
  1697. ' </div>\n' +
  1698. '</div>';
  1699. tClose = $h.closeButton('fileinput-remove');
  1700. tFileIcon = '<i class="glyphicon glyphicon-file"></i>';
  1701. // noinspection HtmlUnknownAttribute
  1702. tCaption = '<input readonly class="file-caption-name form-control {class}">\n';
  1703. //noinspection HtmlUnknownAttribute
  1704. tBtnDefault = '<button type="{type}" title="{title}" class="{css}" ' +
  1705. '{status} {tabIndexConfig}>{icon} {label}</button>';
  1706. //noinspection HtmlUnknownTarget,HtmlUnknownAttribute
  1707. tBtnLink = '<a href="{href}" title="{title}" class="{css}" {status} {tabIndexConfig}>{icon} {label}</a>';
  1708. //noinspection HtmlUnknownAttribute
  1709. tBtnBrowse = '<div class="{css}" {status} {tabIndexConfig}>{icon} {label}</div>';
  1710. tModalLabel = $h.MODAL_ID + 'Label';
  1711. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  1712. 'aria-labelledby="' + tModalLabel + '" {tabIndexConfig}></div>';
  1713. tModal = '<div class="modal-dialog modal-lg{rtl}" role="document">\n' +
  1714. ' <div class="modal-content">\n' +
  1715. ' <div class="modal-header kv-zoom-header">\n' +
  1716. ' <h6 class="modal-title kv-zoom-title" id="' + tModalLabel + '"><span class="kv-zoom-caption"></span> <span class="kv-zoom-size"></span></h6>\n' +
  1717. ' <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  1718. ' </div>\n' +
  1719. ' <div class="floating-buttons"></div>\n' +
  1720. ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
  1721. ' <div class="kv-zoom-description"></div>\n' +
  1722. ' </div>\n' +
  1723. '</div>\n';
  1724. tDescClose = '<button type="button" class="kv-desc-hide" aria-label="Close">{closeIcon}</button>';
  1725. tProgress = '<div class="progress">\n' +
  1726. ' <div class="{class}" role="progressbar"' +
  1727. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  1728. ' {status}\n' +
  1729. ' </div>\n' +
  1730. '</div>{stats}';
  1731. tStats = '<div class="text-primary file-upload-stats">' +
  1732. '<span class="pending-time">{pendingTime}</span> ' +
  1733. '<span class="upload-speed">{uploadSpeed}</span>' +
  1734. '</div>';
  1735. tSize = ' <samp>({sizeText})</samp>';
  1736. tFooter = '<div class="file-thumbnail-footer">\n' +
  1737. ' <div class="file-footer-caption" title="{caption}">\n' +
  1738. ' <div class="file-caption-info">{caption}</div>\n' +
  1739. ' <div class="file-size-info">{size}</div>\n' +
  1740. ' </div>\n' +
  1741. ' {progress}\n{indicator}\n{actions}\n' +
  1742. '</div>';
  1743. tActions = '<div class="file-actions">\n' +
  1744. ' <div class="file-footer-buttons">\n' +
  1745. ' {download} {upload} {delete} {zoom} {other}' +
  1746. ' </div>\n' +
  1747. '</div>\n' +
  1748. '{drag}\n' +
  1749. '<div class="clearfix"></div>';
  1750. //noinspection HtmlUnknownAttribute
  1751. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  1752. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  1753. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  1754. '{uploadIcon}</button>';
  1755. tActionDownload = '<a class="kv-file-download {downloadClass}" title="{downloadTitle}" ' +
  1756. 'href="{downloadUrl}" download="{caption}" target="_blank">{downloadIcon}</a>';
  1757. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  1758. 'title="{zoomTitle}">{zoomIcon}</button>';
  1759. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  1760. tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
  1761. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  1762. ' data-fileid="{fileid}" data-template="{template}" data-zoom="{zoomData}"';
  1763. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  1764. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  1765. tTagAft = '</div>{footer}\n{zoomCache}</div>\n';
  1766. tGeneric = '{content}\n';
  1767. tStyle = ' {style}';
  1768. tHtml = renderObject('html', 'text/html');
  1769. tText = renderObject('text', 'text/plain;charset=UTF-8');
  1770. tPdf = renderObject('pdf', 'application/pdf');
  1771. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{title}" alt="{alt}"' +
  1772. tStyle + '>\n';
  1773. tOffice = '<iframe class="kv-preview-data file-preview-office" ' +
  1774. 'src="https://view.officeapps.live.com/op/embed.aspx?src={data}"' + tStyle + '></iframe>';
  1775. tGdocs = '<iframe class="kv-preview-data file-preview-gdocs" ' +
  1776. 'src="https://docs.google.com/gview?url={data}&embedded=true"' + tStyle + '></iframe>';
  1777. tVideo = '<video class="kv-preview-data file-preview-video" controls' + tStyle + '>\n' +
  1778. '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</video>\n';
  1779. tAudio = '<!--suppress ALL --><audio class="kv-preview-data file-preview-audio" controls' + tStyle + '>\n<source src="{data}" ' +
  1780. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio>\n';
  1781. tFlash = '<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash"' + tStyle + '>\n';
  1782. tObject = '<object class="kv-preview-data file-preview-object file-object {typeCss}" ' +
  1783. 'data="{data}" type="{type}"' + tStyle + '>\n' + '<param name="movie" value="{caption}" />\n' +
  1784. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  1785. tOther = '<div class="kv-preview-data file-preview-other-frame"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  1786. tZoomCache = '<div class="kv-zoom-cache">{zoomContent}</div>';
  1787. vDefaultDim = {width: '100%', height: '100%', 'min-height': '480px'};
  1788. if (self._isPdfRendered()) {
  1789. tPdf = self.pdfRendererTemplate.replace('{renderer}', self._encodeURI(self.pdfRendererUrl));
  1790. }
  1791. self.defaults = {
  1792. layoutTemplates: {
  1793. main1: tMain1,
  1794. main2: tMain2,
  1795. preview: tPreview,
  1796. close: tClose,
  1797. fileIcon: tFileIcon,
  1798. caption: tCaption,
  1799. modalMain: tModalMain,
  1800. modal: tModal,
  1801. descriptionClose: tDescClose,
  1802. progress: tProgress,
  1803. stats: tStats,
  1804. size: tSize,
  1805. footer: tFooter,
  1806. indicator: tIndicator,
  1807. actions: tActions,
  1808. actionDelete: tActionDelete,
  1809. actionUpload: tActionUpload,
  1810. actionDownload: tActionDownload,
  1811. actionZoom: tActionZoom,
  1812. actionDrag: tActionDrag,
  1813. btnDefault: tBtnDefault,
  1814. btnLink: tBtnLink,
  1815. btnBrowse: tBtnBrowse,
  1816. zoomCache: tZoomCache
  1817. },
  1818. previewMarkupTags: {
  1819. tagBefore1: tTagBef1,
  1820. tagBefore2: tTagBef2,
  1821. tagAfter: tTagAft
  1822. },
  1823. previewContentTemplates: {
  1824. generic: tGeneric,
  1825. html: tHtml,
  1826. image: tImage,
  1827. text: tText,
  1828. office: tOffice,
  1829. gdocs: tGdocs,
  1830. video: tVideo,
  1831. audio: tAudio,
  1832. flash: tFlash,
  1833. object: tObject,
  1834. pdf: tPdf,
  1835. other: tOther
  1836. },
  1837. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  1838. previewTemplates: {},
  1839. previewSettings: {
  1840. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1841. html: {width: '213px', height: '160px'},
  1842. text: {width: '213px', height: '160px'},
  1843. office: {width: '213px', height: '160px'},
  1844. gdocs: {width: '213px', height: '160px'},
  1845. video: {width: '213px', height: '160px'},
  1846. audio: {width: '100%', height: '30px'},
  1847. flash: {width: '213px', height: '160px'},
  1848. object: {width: '213px', height: '160px'},
  1849. pdf: {width: '100%', height: '160px', 'position': 'relative'},
  1850. other: {width: '213px', height: '160px'}
  1851. },
  1852. previewSettingsSmall: {
  1853. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1854. html: {width: '100%', height: '160px'},
  1855. text: {width: '100%', height: '160px'},
  1856. office: {width: '100%', height: '160px'},
  1857. gdocs: {width: '100%', height: '160px'},
  1858. video: {width: '100%', height: 'auto'},
  1859. audio: {width: '100%', height: '30px'},
  1860. flash: {width: '100%', height: 'auto'},
  1861. object: {width: '100%', height: 'auto'},
  1862. pdf: {width: '100%', height: '160px'},
  1863. other: {width: '100%', height: '160px'}
  1864. },
  1865. previewZoomSettings: {
  1866. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1867. html: vDefaultDim,
  1868. text: vDefaultDim,
  1869. office: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1870. gdocs: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1871. video: {width: 'auto', height: '100%', 'max-width': '100%'},
  1872. audio: {width: '100%', height: '30px'},
  1873. flash: {width: 'auto', height: '480px'},
  1874. object: {width: 'auto', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1875. pdf: vDefaultDim,
  1876. other: {width: 'auto', height: '100%', 'min-height': '480px'}
  1877. },
  1878. mimeTypeAliases: {
  1879. 'video/quicktime': 'video/mp4'
  1880. },
  1881. fileTypeSettings: {
  1882. image: function (vType, vName) {
  1883. return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) ||
  1884. $h.compare(vName, /\.(gif|png|jpe?g)$/i));
  1885. },
  1886. html: function (vType, vName) {
  1887. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  1888. },
  1889. office: function (vType, vName) {
  1890. return $h.compare(vType, /(word|excel|powerpoint|office)$/i) ||
  1891. $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i);
  1892. },
  1893. gdocs: function (vType, vName) {
  1894. return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) ||
  1895. $h.compare(vName,
  1896. /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i);
  1897. },
  1898. text: function (vType, vName) {
  1899. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  1900. $h.compare(vName, /\.(txt|md|nfo|ini|json|php|js|css)$/i);
  1901. },
  1902. video: function (vType, vName) {
  1903. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  1904. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  1905. },
  1906. audio: function (vType, vName) {
  1907. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  1908. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  1909. },
  1910. flash: function (vType, vName) {
  1911. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName,
  1912. /\.(swf)$/i);
  1913. },
  1914. pdf: function (vType, vName) {
  1915. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  1916. },
  1917. object: function () {
  1918. return true;
  1919. },
  1920. other: function () {
  1921. return true;
  1922. }
  1923. },
  1924. fileActionSettings: {
  1925. showRemove: true,
  1926. showUpload: true,
  1927. showDownload: true,
  1928. showZoom: true,
  1929. showDrag: true,
  1930. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  1931. removeClass: defBtnCss1,
  1932. removeErrorClass: 'btn btn-sm btn-kv btn-danger',
  1933. removeTitle: 'Remove file',
  1934. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  1935. uploadClass: defBtnCss1,
  1936. uploadTitle: 'Upload file',
  1937. uploadRetryIcon: '<i class="glyphicon glyphicon-repeat"></i>',
  1938. uploadRetryTitle: 'Retry upload',
  1939. downloadIcon: '<i class="glyphicon glyphicon-download"></i>',
  1940. downloadClass: defBtnCss1,
  1941. downloadTitle: 'Download file',
  1942. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  1943. zoomClass: defBtnCss1,
  1944. zoomTitle: 'View Details',
  1945. dragIcon: '<i class="glyphicon glyphicon-move"></i>',
  1946. dragClass: 'text-primary',
  1947. dragTitle: 'Move / Rearrange',
  1948. dragSettings: {},
  1949. indicatorNew: '<i class="glyphicon glyphicon-plus-sign text-warning"></i>',
  1950. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  1951. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  1952. indicatorLoading: '<i class="glyphicon glyphicon-hourglass text-muted"></i>',
  1953. indicatorPaused: '<i class="glyphicon glyphicon-pause text-primary"></i>',
  1954. indicatorNewTitle: 'Not uploaded yet',
  1955. indicatorSuccessTitle: 'Uploaded',
  1956. indicatorErrorTitle: 'Upload Error',
  1957. indicatorLoadingTitle: 'Uploading &hellip;',
  1958. indicatorPausedTitle: 'Upload Paused'
  1959. }
  1960. };
  1961. $.each(self.defaults, function (key, setting) {
  1962. if (key === 'allowedPreviewTypes') {
  1963. if (self.allowedPreviewTypes === undefined) {
  1964. self.allowedPreviewTypes = setting;
  1965. }
  1966. return;
  1967. }
  1968. self[key] = $.extend(true, {}, setting, self[key]);
  1969. });
  1970. self._initPreviewTemplates();
  1971. },
  1972. _initPreviewTemplates: function () {
  1973. var self = this, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  1974. $.each(self.previewContentTemplates, function (key, value) {
  1975. if ($h.isEmpty(self.previewTemplates[key])) {
  1976. tagBef = tags.tagBefore2;
  1977. if (key === 'generic' || key === 'image') {
  1978. tagBef = tags.tagBefore1;
  1979. }
  1980. if (self._isPdfRendered() && key === 'pdf') {
  1981. tagBef = tagBef.replace('kv-file-content', 'kv-file-content kv-pdf-rendered');
  1982. }
  1983. self.previewTemplates[key] = tagBef + value + tagAft;
  1984. }
  1985. });
  1986. },
  1987. _initPreviewCache: function () {
  1988. var self = this;
  1989. self.previewCache = {
  1990. data: {},
  1991. init: function () {
  1992. var content = self.initialPreview;
  1993. if (content.length > 0 && !$h.isArray(content)) {
  1994. content = content.split(self.initialPreviewDelimiter);
  1995. }
  1996. self.previewCache.data = {
  1997. content: content,
  1998. config: self.initialPreviewConfig,
  1999. tags: self.initialPreviewThumbTags
  2000. };
  2001. },
  2002. count: function (skipNull) {
  2003. if (!self.previewCache.data || !self.previewCache.data.content) {
  2004. return 0;
  2005. }
  2006. if (skipNull) {
  2007. var chk = self.previewCache.data.content.filter(function (n) {
  2008. return n !== null;
  2009. });
  2010. return chk.length;
  2011. }
  2012. return self.previewCache.data.content.length;
  2013. },
  2014. get: function (i, isDisabled) {
  2015. var ind = $h.INIT_FLAG + i, data = self.previewCache.data, config = data.config[i],
  2016. content = data.content[i], out, $tmp, cat, ftr,
  2017. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  2018. a = config ? {title: config.title || null, alt: config.alt || null} : {title: null, alt: null},
  2019. parseTemplate = function (cat, dat, fname, ftype, ftr, ind, fclass, t) {
  2020. var fc = ' file-preview-initial ' + $h.SORT_CSS + (fclass ? ' ' + fclass : ''),
  2021. id = self.previewInitId + '-' + ind,
  2022. fileId = config && config.fileId || id;
  2023. /** @namespace config.zoomData */
  2024. return self._generatePreviewTemplate(cat, dat, fname, ftype, id, fileId, false, null, fc,
  2025. ftr, ind, t, a, config && config.zoomData || dat);
  2026. };
  2027. if (!content || !content.length) {
  2028. return '';
  2029. }
  2030. isDisabled = isDisabled === undefined ? true : isDisabled;
  2031. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  2032. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  2033. ftype = $h.ifSet('filetype', config, cat);
  2034. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  2035. frameClass = $h.ifSet('frameClass', config);
  2036. if (asData) {
  2037. out = parseTemplate(cat, content, fname, ftype, ftr, ind, frameClass);
  2038. } else {
  2039. out = parseTemplate('generic', content, fname, ftype, ftr, ind, frameClass, cat)
  2040. .setTokens({'content': data.content[i]});
  2041. }
  2042. if (data.tags.length && data.tags[i]) {
  2043. out = $h.replaceTags(out, data.tags[i]);
  2044. }
  2045. /** @namespace config.frameAttr */
  2046. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  2047. $tmp = $h.createElement(out);
  2048. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  2049. out = $tmp.html();
  2050. $tmp.remove();
  2051. }
  2052. return out;
  2053. },
  2054. clean: function (data) {
  2055. data.content = $h.cleanArray(data.content);
  2056. data.config = $h.cleanArray(data.config);
  2057. data.tags = $h.cleanArray(data.tags);
  2058. self.previewCache.data = data;
  2059. },
  2060. add: function (content, config, tags, append) {
  2061. var data = self.previewCache.data, index;
  2062. if (!content || !content.length) {
  2063. return 0;
  2064. }
  2065. index = content.length - 1;
  2066. if (!$h.isArray(content)) {
  2067. content = content.split(self.initialPreviewDelimiter);
  2068. }
  2069. if (append && data.content) {
  2070. index = data.content.push(content[0]) - 1;
  2071. data.config[index] = config;
  2072. data.tags[index] = tags;
  2073. } else {
  2074. data.content = content;
  2075. data.config = config;
  2076. data.tags = tags;
  2077. }
  2078. self.previewCache.clean(data);
  2079. return index;
  2080. },
  2081. set: function (content, config, tags, append) {
  2082. var data = self.previewCache.data, i, chk;
  2083. if (!content || !content.length) {
  2084. return;
  2085. }
  2086. if (!$h.isArray(content)) {
  2087. content = content.split(self.initialPreviewDelimiter);
  2088. }
  2089. chk = content.filter(function (n) {
  2090. return n !== null;
  2091. });
  2092. if (!chk.length) {
  2093. return;
  2094. }
  2095. if (data.content === undefined) {
  2096. data.content = [];
  2097. }
  2098. if (data.config === undefined) {
  2099. data.config = [];
  2100. }
  2101. if (data.tags === undefined) {
  2102. data.tags = [];
  2103. }
  2104. if (append) {
  2105. for (i = 0; i < content.length; i++) {
  2106. if (content[i]) {
  2107. data.content.push(content[i]);
  2108. }
  2109. }
  2110. for (i = 0; i < config.length; i++) {
  2111. if (config[i]) {
  2112. data.config.push(config[i]);
  2113. }
  2114. }
  2115. for (i = 0; i < tags.length; i++) {
  2116. if (tags[i]) {
  2117. data.tags.push(tags[i]);
  2118. }
  2119. }
  2120. } else {
  2121. data.content = content;
  2122. data.config = config;
  2123. data.tags = tags;
  2124. }
  2125. self.previewCache.clean(data);
  2126. },
  2127. unset: function (index) {
  2128. var chk = self.previewCache.count(), rev = self.reversePreviewOrder;
  2129. if (!chk) {
  2130. return;
  2131. }
  2132. if (chk === 1) {
  2133. self.previewCache.data.content = [];
  2134. self.previewCache.data.config = [];
  2135. self.previewCache.data.tags = [];
  2136. self.initialPreview = [];
  2137. self.initialPreviewConfig = [];
  2138. self.initialPreviewThumbTags = [];
  2139. return;
  2140. }
  2141. self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev);
  2142. self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev);
  2143. self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev);
  2144. var data = $.extend(true, {}, self.previewCache.data);
  2145. self.previewCache.clean(data);
  2146. },
  2147. out: function () {
  2148. var html = '', caption, len = self.previewCache.count(), i, content;
  2149. if (len === 0) {
  2150. return {content: '', caption: ''};
  2151. }
  2152. for (i = 0; i < len; i++) {
  2153. content = self.previewCache.get(i);
  2154. html = self.reversePreviewOrder ? (content + html) : (html + content);
  2155. }
  2156. caption = self._getMsgSelected(len);
  2157. return {content: html, caption: caption};
  2158. },
  2159. footer: function (i, isDisabled, size) {
  2160. var data = self.previewCache.data || {};
  2161. if ($h.isEmpty(data.content)) {
  2162. return '';
  2163. }
  2164. if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
  2165. data.config[i] = {};
  2166. }
  2167. isDisabled = isDisabled === undefined ? true : isDisabled;
  2168. var config = data.config[i], caption = $h.ifSet('caption', config), a,
  2169. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  2170. key = $h.ifSet('key', config, null), fileId = $h.ifSet('fileId', config, null),
  2171. fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false,
  2172. downloadInitialUrl = !self.initialPreviewDownloadUrl ? '' :
  2173. self.initialPreviewDownloadUrl + '?key=' + key + (fileId ? '&fileId=' + fileId : ''),
  2174. dUrl = config.downloadUrl || downloadInitialUrl,
  2175. dFil = config.filename || config.caption || '',
  2176. initPreviewShowDwl = !!(dUrl),
  2177. sDel = $h.ifSet('showRemove', config, initPreviewShowDel),
  2178. sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
  2179. sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  2180. sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  2181. dis = (url === false) && isDisabled;
  2182. sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
  2183. a = self._renderFileActions(config, false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
  2184. return self._getLayoutTemplate('footer').setTokens({
  2185. 'progress': self._renderThumbProgress(),
  2186. 'actions': a,
  2187. 'caption': caption,
  2188. 'size': self._getSize(size),
  2189. 'width': width,
  2190. 'indicator': ''
  2191. });
  2192. }
  2193. };
  2194. self.previewCache.init();
  2195. },
  2196. _isPdfRendered: function () {
  2197. var self = this, useLib = self.usePdfRenderer,
  2198. flag = typeof useLib === 'function' ? useLib() : !!useLib;
  2199. return flag && self.pdfRendererUrl;
  2200. },
  2201. _handler: function ($el, event, callback) {
  2202. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  2203. if (!$el || !$el.length) {
  2204. return;
  2205. }
  2206. $el.off(ev).on(ev, callback);
  2207. },
  2208. _encodeURI: function (vUrl) {
  2209. var self = this;
  2210. return self.encodeUrl ? encodeURI(vUrl) : vUrl;
  2211. },
  2212. _log: function (msg, tokens) {
  2213. var self = this, id = self.$element.attr('id');
  2214. if (!self.showConsoleLogs) {
  2215. return;
  2216. }
  2217. if (id) {
  2218. msg = '"' + id + '": ' + msg;
  2219. }
  2220. msg = 'bootstrap-fileinput: ' + msg;
  2221. if (typeof tokens === 'object') {
  2222. msg = msg.setTokens(tokens);
  2223. }
  2224. if (window.console && typeof window.console.log !== 'undefined') {
  2225. window.console.log(msg);
  2226. } else {
  2227. window.alert(msg);
  2228. }
  2229. },
  2230. _validate: function () {
  2231. var self = this, status = self.$element.attr('type') === 'file';
  2232. if (!status) {
  2233. self._log($h.logMessages.badInputType);
  2234. }
  2235. return status;
  2236. },
  2237. _errorsExist: function () {
  2238. var self = this, $err, $errList = self.$errorContainer.find('li');
  2239. if ($errList.length) {
  2240. return true;
  2241. }
  2242. $err = $h.createElement(self.$errorContainer.html());
  2243. $err.find('.kv-error-close').remove();
  2244. $err.find('ul').remove();
  2245. return !!$.trim($err.text()).length;
  2246. },
  2247. _errorHandler: function (evt, caption) {
  2248. var self = this, err = evt.target.error, showError = function (msg) {
  2249. self._showError(msg.replace('{name}', caption));
  2250. };
  2251. /** @namespace err.NOT_FOUND_ERR */
  2252. /** @namespace err.SECURITY_ERR */
  2253. /** @namespace err.NOT_READABLE_ERR */
  2254. if (err.code === err.NOT_FOUND_ERR) {
  2255. showError(self.msgFileNotFound);
  2256. } else {
  2257. if (err.code === err.SECURITY_ERR) {
  2258. showError(self.msgFileSecured);
  2259. } else {
  2260. if (err.code === err.NOT_READABLE_ERR) {
  2261. showError(self.msgFileNotReadable);
  2262. } else {
  2263. if (err.code === err.ABORT_ERR) {
  2264. showError(self.msgFilePreviewAborted);
  2265. } else {
  2266. showError(self.msgFilePreviewError);
  2267. }
  2268. }
  2269. }
  2270. }
  2271. },
  2272. _addError: function (msg) {
  2273. var self = this, $error = self.$errorContainer;
  2274. if (msg && $error.length) {
  2275. $h.setHtml($error, self.errorCloseButton + msg);
  2276. self._handler($error.find('.kv-error-close'), 'click', function () {
  2277. setTimeout(function () {
  2278. if (self.showPreview && !self.getFrames().length) {
  2279. self.clear();
  2280. }
  2281. $error.fadeOut('slow');
  2282. }, self.processDelay);
  2283. });
  2284. }
  2285. },
  2286. _setValidationError: function (css) {
  2287. var self = this;
  2288. css = (css ? css + ' ' : '') + 'has-error';
  2289. self.$container.removeClass(css).addClass('has-error');
  2290. $h.addCss(self.$caption, 'is-invalid');
  2291. },
  2292. _resetErrors: function (fade) {
  2293. var self = this, $error = self.$errorContainer, history = self.resumableUploadOptions.retainErrorHistory;
  2294. if (self.isPersistentError || (self.enableResumableUpload && history)) {
  2295. return;
  2296. }
  2297. self.isError = false;
  2298. self.$container.removeClass('has-error');
  2299. self.$caption.removeClass('is-invalid is-valid file-processing');
  2300. $error.html('');
  2301. if (fade) {
  2302. $error.fadeOut('slow');
  2303. } else {
  2304. $error.hide();
  2305. }
  2306. },
  2307. _showFolderError: function (folders) {
  2308. var self = this, $error = self.$errorContainer, msg;
  2309. if (!folders) {
  2310. return;
  2311. }
  2312. if (!self.isAjaxUpload) {
  2313. self._clearFileInput();
  2314. }
  2315. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  2316. self._addError(msg);
  2317. self._setValidationError();
  2318. $error.fadeIn(self.fadeDelay);
  2319. self._raise('filefoldererror', [folders, msg]);
  2320. },
  2321. _showFileError: function (msg, params, event) {
  2322. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  2323. fId = params && params.fileId || '', e = params && params.id ?
  2324. '<li data-thumb-id="' + params.id + '" data-file-id="' + fId + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  2325. if ($error.find('ul').length === 0) {
  2326. self._addError('<ul>' + e + '</ul>');
  2327. } else {
  2328. $error.find('ul').append(e);
  2329. }
  2330. $error.fadeIn(self.fadeDelay);
  2331. self._raise(ev, [params, msg]);
  2332. self._setValidationError('file-input-new');
  2333. return true;
  2334. },
  2335. _showError: function (msg, params, event) {
  2336. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  2337. params = params || {};
  2338. params.reader = self.reader;
  2339. self._addError(msg);
  2340. $error.fadeIn(self.fadeDelay);
  2341. self._raise(ev, [params, msg]);
  2342. if (!self.isAjaxUpload) {
  2343. self._clearFileInput();
  2344. }
  2345. self._setValidationError('file-input-new');
  2346. self.$btnUpload.attr('disabled', true);
  2347. return true;
  2348. },
  2349. _noFilesError: function (params) {
  2350. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  2351. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  2352. $error = self.$errorContainer;
  2353. msg = '<li>' + msg + '</li>';
  2354. if ($error.find('ul').length === 0) {
  2355. self._addError('<ul>' + msg + '</ul>');
  2356. } else {
  2357. $error.find('ul').append(msg);
  2358. }
  2359. self.isError = true;
  2360. self._updateFileDetails(0);
  2361. $error.fadeIn(self.fadeDelay);
  2362. self._raise('fileerror', [params, msg]);
  2363. self._clearFileInput();
  2364. self._setValidationError();
  2365. },
  2366. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  2367. /** @namespace jqXHR.responseJSON */
  2368. var self = this, errMsg = $.trim(errorThrown + ''), textPre, errText, text;
  2369. errText = jqXHR.responseJSON && jqXHR.responseJSON.error ? jqXHR.responseJSON.error.toString() : '';
  2370. text = errText ? errText : jqXHR.responseText;
  2371. if (self.cancelling && self.msgUploadAborted) {
  2372. errMsg = self.msgUploadAborted;
  2373. }
  2374. if (self.showAjaxErrorDetails && text) {
  2375. if (errText) {
  2376. errMsg = $.trim(errText + '');
  2377. } else {
  2378. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  2379. textPre = text.length ? '<pre>' + text + '</pre>' : '';
  2380. errMsg += errMsg ? textPre : text;
  2381. }
  2382. }
  2383. if (!errMsg) {
  2384. errMsg = self.msgAjaxError.replace('{operation}', operation);
  2385. }
  2386. self.cancelling = false;
  2387. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  2388. },
  2389. _parseFileType: function (type, name) {
  2390. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  2391. if (type === 'application/text-plain') {
  2392. return 'text';
  2393. }
  2394. for (i = 0; i < types.length; i++) {
  2395. cat = types[i];
  2396. isValid = self.fileTypeSettings[cat];
  2397. vType = isValid(type, name) ? cat : '';
  2398. if (!$h.isEmpty(vType)) {
  2399. return vType;
  2400. }
  2401. }
  2402. return 'other';
  2403. },
  2404. _getPreviewIcon: function (fname) {
  2405. var self = this, ext, out = null;
  2406. if (fname && fname.indexOf('.') > -1) {
  2407. ext = fname.split('.').pop();
  2408. if (self.previewFileIconSettings) {
  2409. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  2410. }
  2411. if (self.previewFileExtSettings) {
  2412. $.each(self.previewFileExtSettings, function (key, func) {
  2413. if (self.previewFileIconSettings[key] && func(ext)) {
  2414. out = self.previewFileIconSettings[key];
  2415. //noinspection UnnecessaryReturnStatementJS
  2416. return;
  2417. }
  2418. });
  2419. }
  2420. }
  2421. return out || self.previewFileIcon;
  2422. },
  2423. _parseFilePreviewIcon: function (content, fname) {
  2424. var self = this, icn = self._getPreviewIcon(fname), out = content;
  2425. if (out.indexOf('{previewFileIcon}') > -1) {
  2426. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  2427. }
  2428. return out;
  2429. },
  2430. _raise: function (event, params) {
  2431. var self = this, e = $.Event(event);
  2432. if (params !== undefined) {
  2433. self.$element.trigger(e, params);
  2434. } else {
  2435. self.$element.trigger(e);
  2436. }
  2437. var out = e.result, isAborted = out === false;
  2438. if (e.isDefaultPrevented() || isAborted) {
  2439. return false;
  2440. }
  2441. if (e.type === 'filebatchpreupload' && (out || isAborted)) {
  2442. self.ajaxAborted = out;
  2443. return false;
  2444. }
  2445. switch (event) {
  2446. // ignore these events
  2447. case 'filebatchuploadcomplete':
  2448. case 'filebatchuploadsuccess':
  2449. case 'fileuploaded':
  2450. case 'fileclear':
  2451. case 'filecleared':
  2452. case 'filereset':
  2453. case 'fileerror':
  2454. case 'filefoldererror':
  2455. case 'fileuploaderror':
  2456. case 'filebatchuploaderror':
  2457. case 'filedeleteerror':
  2458. case 'filecustomerror':
  2459. case 'filesuccessremove':
  2460. break;
  2461. // receive data response via `filecustomerror` event`
  2462. default:
  2463. if (!self.ajaxAborted) {
  2464. self.ajaxAborted = out;
  2465. }
  2466. break;
  2467. }
  2468. return true;
  2469. },
  2470. _listenFullScreen: function (isFullScreen) {
  2471. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  2472. if (!$modal || !$modal.length) {
  2473. return;
  2474. }
  2475. $btnFull = $modal && $modal.find('.btn-kv-fullscreen');
  2476. $btnBord = $modal && $modal.find('.btn-kv-borderless');
  2477. if (!$btnFull.length || !$btnBord.length) {
  2478. return;
  2479. }
  2480. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2481. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2482. if (isFullScreen) {
  2483. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2484. } else {
  2485. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2486. }
  2487. if ($modal.hasClass('file-zoom-fullscreen')) {
  2488. self._maximizeZoomDialog();
  2489. } else {
  2490. if (isFullScreen) {
  2491. self._maximizeZoomDialog();
  2492. } else {
  2493. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2494. }
  2495. }
  2496. },
  2497. _listen: function () {
  2498. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEv;
  2499. self._handler($el, 'click', function (e) {
  2500. self._initFileSelected();
  2501. if ($el.hasClass('file-no-browse')) {
  2502. if ($el.data('zoneClicked')) {
  2503. $el.data('zoneClicked', false);
  2504. } else {
  2505. e.preventDefault();
  2506. }
  2507. }
  2508. });
  2509. self._handler($el, 'change', $.proxy(self._change, self));
  2510. self._handler(self.$caption, 'paste', $.proxy(self.paste, self));
  2511. if (self.showBrowse) {
  2512. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  2513. self._handler(self.$btnFile, 'keypress', function (e) {
  2514. var keycode = e.keyCode || e.which
  2515. if (keycode === 13) {
  2516. $el.trigger('click');
  2517. self._browse(e);
  2518. }
  2519. });
  2520. }
  2521. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  2522. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  2523. self._handler($cont.find('.fileinput-pause'), 'click', $.proxy(self.pause, self));
  2524. self._initDragDrop();
  2525. self._handler($form, 'reset', $.proxy(self.clear, self));
  2526. if (!self.isAjaxUpload) {
  2527. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  2528. }
  2529. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  2530. self._handler($(window), 'resize', function () {
  2531. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  2532. });
  2533. fullScreenEv = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  2534. self._handler($(document), fullScreenEv, function () {
  2535. self._listenFullScreen($h.checkFullScreen());
  2536. });
  2537. self.$caption.on('focus', function () {
  2538. self.$captionContainer.focus();
  2539. });
  2540. self._autoFitContent();
  2541. self._initClickable();
  2542. self._refreshPreview();
  2543. },
  2544. _autoFitContent: function () {
  2545. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  2546. self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
  2547. (self.previewSettings || self.defaults.previewSettings), sel;
  2548. $.each(config, function (cat, settings) {
  2549. sel = '.file-preview-frame .file-preview-' + cat;
  2550. self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
  2551. });
  2552. },
  2553. _scanDroppedItems: function (item, files, path) {
  2554. path = path || '';
  2555. var self = this, i, dirReader, readDir, errorHandler = function (e) {
  2556. self._log($h.logMessages.badDroppedFiles);
  2557. self._log(e);
  2558. };
  2559. if (item.isFile) {
  2560. item.file(function (file) {
  2561. if (path) {
  2562. file.newPath = path + file.name;
  2563. }
  2564. files.push(file);
  2565. }, errorHandler);
  2566. } else {
  2567. if (item.isDirectory) {
  2568. dirReader = item.createReader();
  2569. readDir = function () {
  2570. dirReader.readEntries(function (entries) {
  2571. if (entries && entries.length > 0) {
  2572. for (i = 0; i < entries.length; i++) {
  2573. self._scanDroppedItems(entries[i], files, path + item.name + '/');
  2574. }
  2575. // recursively call readDir() again, since browser can only handle first 100 entries.
  2576. readDir();
  2577. }
  2578. return null;
  2579. }, errorHandler);
  2580. };
  2581. readDir();
  2582. }
  2583. }
  2584. },
  2585. _initDragDrop: function () {
  2586. var self = this, $zone = self.$dropZone;
  2587. if (self.dropZoneEnabled && self.showPreview) {
  2588. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  2589. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  2590. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  2591. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  2592. }
  2593. },
  2594. _zoneDragDropInit: function (e) {
  2595. e.stopPropagation();
  2596. e.preventDefault();
  2597. },
  2598. _zoneDragEnter: function (e) {
  2599. var self = this, dt = e.originalEvent.dataTransfer, hasFiles = $.inArray('Files', dt.types) > -1;
  2600. self._zoneDragDropInit(e);
  2601. if (self.isDisabled || !hasFiles) {
  2602. dt.effectAllowed = 'none';
  2603. dt.dropEffect = 'none';
  2604. return;
  2605. }
  2606. dt.dropEffect = 'copy';
  2607. if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dt.types.Files})) {
  2608. $h.addCss(self.$dropZone, 'file-highlighted');
  2609. }
  2610. },
  2611. _zoneDragLeave: function (e) {
  2612. var self = this;
  2613. self._zoneDragDropInit(e);
  2614. if (self.isDisabled) {
  2615. return;
  2616. }
  2617. if (self._raise('fileDragLeave', {'sourceEvent': e})) {
  2618. self.$dropZone.removeClass('file-highlighted');
  2619. }
  2620. },
  2621. _dropFiles: function (e, files) {
  2622. var self = this, $el = self.$element;
  2623. if (!self.isAjaxUpload) {
  2624. self.changeTriggered = true;
  2625. $el.get(0).files = files;
  2626. setTimeout(function () {
  2627. self.changeTriggered = false;
  2628. $el.trigger('change' + self.namespace);
  2629. }, self.processDelay);
  2630. } else {
  2631. self._change(e, files);
  2632. }
  2633. self.$dropZone.removeClass('file-highlighted');
  2634. },
  2635. _zoneDrop: function (e) {
  2636. /** @namespace e.originalEvent.dataTransfer */
  2637. var self = this, i, $el = self.$element, dt = e.originalEvent.dataTransfer,
  2638. files = dt.files, items = dt.items, folders = $h.getDragDropFolders(items);
  2639. e.preventDefault();
  2640. if (self.isDisabled || $h.isEmpty(files)) {
  2641. return;
  2642. }
  2643. if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) {
  2644. return;
  2645. }
  2646. if (folders > 0) {
  2647. if (!self.isAjaxUpload) {
  2648. self._showFolderError(folders);
  2649. return;
  2650. }
  2651. files = [];
  2652. for (i = 0; i < items.length; i++) {
  2653. var item = items[i].webkitGetAsEntry();
  2654. if (item) {
  2655. self._scanDroppedItems(item, files);
  2656. }
  2657. }
  2658. setTimeout(function () {
  2659. self._dropFiles(e, files);
  2660. }, 500);
  2661. } else {
  2662. self._dropFiles(e, files);
  2663. }
  2664. },
  2665. _uploadClick: function (e) {
  2666. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  2667. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  2668. if (e && e.isDefaultPrevented()) {
  2669. return;
  2670. }
  2671. if (!self.isAjaxUpload) {
  2672. if (isEnabled && $btn.attr('type') !== 'submit') {
  2673. $form = $btn.closest('form');
  2674. // downgrade to normal form submit if possible
  2675. if ($form.length) {
  2676. $form.trigger('submit');
  2677. }
  2678. e.preventDefault();
  2679. }
  2680. return;
  2681. }
  2682. e.preventDefault();
  2683. if (isEnabled) {
  2684. self.upload();
  2685. }
  2686. },
  2687. _submitForm: function () {
  2688. var self = this;
  2689. return self._isFileSelectionValid() && !self._abort({});
  2690. },
  2691. _clearPreview: function () {
  2692. var self = this,
  2693. $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
  2694. $thumbs.each(function () {
  2695. var $thumb = $(this);
  2696. $thumb.remove();
  2697. });
  2698. if (!self.getFrames().length || !self.showPreview) {
  2699. self._resetUpload();
  2700. }
  2701. self._validateDefaultPreview();
  2702. },
  2703. _initSortable: function () {
  2704. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS, $cont, $body = $('body'),
  2705. $html = $('html'), rev = self.reversePreviewOrder, Sortable = window.Sortable, beginGrab, endGrab;
  2706. if (!Sortable || $el.find(selector).length === 0) {
  2707. return;
  2708. }
  2709. $cont = $body.length ? $body : ($html.length ? $html : self.$container);
  2710. beginGrab = function () {
  2711. $cont.addClass('file-grabbing');
  2712. };
  2713. endGrab = function () {
  2714. $cont.removeClass('file-grabbing');
  2715. };
  2716. settings = {
  2717. handle: '.drag-handle-init',
  2718. dataIdAttr: 'data-fileid',
  2719. animation: 600,
  2720. draggable: selector,
  2721. scroll: false,
  2722. forceFallback: true,
  2723. onChoose: beginGrab,
  2724. onStart: beginGrab,
  2725. onUnchoose: endGrab,
  2726. onEnd: endGrab,
  2727. onSort: function (e) {
  2728. var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0, len = self.initialPreviewConfig.length,
  2729. exceedsLast = len > 0 && newIndex >= len, $item = $(e.item), $first;
  2730. if (exceedsLast) {
  2731. newIndex = len - 1;
  2732. }
  2733. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev);
  2734. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev);
  2735. self.previewCache.init();
  2736. self.getFrames('.file-preview-initial').each(function () {
  2737. $(this).attr('data-fileindex', $h.INIT_FLAG + i);
  2738. i++;
  2739. });
  2740. if (exceedsLast) {
  2741. $first = self.getFrames(':not(.file-preview-initial):first');
  2742. if ($first.length) {
  2743. $item.slideUp(function () {
  2744. $item.insertBefore($first).slideDown();
  2745. });
  2746. }
  2747. }
  2748. self._raise('filesorted', {
  2749. previewId: $item.attr('id'),
  2750. 'oldIndex': oldIndex,
  2751. 'newIndex': newIndex,
  2752. stack: self.initialPreviewConfig
  2753. });
  2754. },
  2755. };
  2756. $.extend(true, settings, self.fileActionSettings.dragSettings);
  2757. if (self.sortable) {
  2758. self.sortable.destroy();
  2759. }
  2760. self.sortable = Sortable.create($el[0], settings);
  2761. },
  2762. _setPreviewContent: function (content) {
  2763. var self = this;
  2764. $h.setHtml(self.$preview, content);
  2765. self._autoFitContent();
  2766. },
  2767. _initPreviewImageOrientations: function () {
  2768. var self = this, i = 0, canOrientImage = self.canOrientImage;
  2769. if (!self.autoOrientImageInitial && !canOrientImage) {
  2770. return;
  2771. }
  2772. self.getFrames('.file-preview-initial').each(function () {
  2773. var $thumb = $(this), $img, $zoomImg, id, config = self.initialPreviewConfig[i];
  2774. /** @namespace config.exif */
  2775. if (config && config.exif && config.exif.Orientation) {
  2776. id = $thumb.attr('id');
  2777. $img = $thumb.find('>.kv-file-content img');
  2778. $zoomImg = self._getZoom(id, ' >.kv-file-content img');
  2779. if (canOrientImage) {
  2780. $img.css('image-orientation', (self.autoOrientImageInitial ? 'from-image' : 'none'));
  2781. } else {
  2782. self.setImageOrientation($img, $zoomImg, config.exif.Orientation, $thumb);
  2783. }
  2784. }
  2785. i++;
  2786. });
  2787. },
  2788. _initPreview: function (isInit) {
  2789. var self = this, cap = self.initialCaption || '', out;
  2790. if (!self.previewCache.count(true)) {
  2791. self._clearPreview();
  2792. if (isInit) {
  2793. self._setCaption(cap);
  2794. } else {
  2795. self._initCaption();
  2796. }
  2797. return;
  2798. }
  2799. out = self.previewCache.out();
  2800. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  2801. self._setPreviewContent(out.content);
  2802. self._setInitThumbAttr();
  2803. self._setCaption(cap);
  2804. self._initSortable();
  2805. if (!$h.isEmpty(out.content)) {
  2806. self.$container.removeClass('file-input-new');
  2807. }
  2808. self._initPreviewImageOrientations();
  2809. },
  2810. _getZoomButton: function (type) {
  2811. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  2812. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', tag = $h.isBs(5) ? 'bs-' : '',
  2813. params = title + (type === 'close' ? ' data-' + tag + 'dismiss="modal" aria-hidden="true"' : '');
  2814. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  2815. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  2816. }
  2817. return '<button type="button" class="' + css + ' btn-kv-' + type + '"' + params + '>' + label + '</button>';
  2818. },
  2819. _getModalContent: function () {
  2820. var self = this;
  2821. return self._getLayoutTemplate('modal').setTokens({
  2822. 'rtl': self.rtl ? ' kv-rtl' : '',
  2823. 'zoomFrameClass': self.frameClass,
  2824. 'prev': self._getZoomButton('prev'),
  2825. 'next': self._getZoomButton('next'),
  2826. 'toggleheader': self._getZoomButton('toggleheader'),
  2827. 'fullscreen': self._getZoomButton('fullscreen'),
  2828. 'borderless': self._getZoomButton('borderless'),
  2829. 'close': self._getZoomButton('close')
  2830. });
  2831. },
  2832. _listenModalEvent: function (event) {
  2833. var self = this, $modal = self.$modal, getParams = function (e) {
  2834. return {
  2835. sourceEvent: e,
  2836. previewId: $modal.data('previewId'),
  2837. modal: $modal
  2838. };
  2839. };
  2840. $modal.on(event + '.bs.modal', function (e) {
  2841. if (e.namespace !== 'bs.modal') {
  2842. return;
  2843. }
  2844. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  2845. if ($modal.data('fileinputPluginId') === self.$element.attr('id')) {
  2846. self._raise('filezoom' + event, getParams(e));
  2847. }
  2848. if (event === 'shown') {
  2849. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2850. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2851. if ($modal.hasClass('file-zoom-fullscreen')) {
  2852. self._maximizeZoomDialog();
  2853. if ($h.checkFullScreen()) {
  2854. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2855. } else {
  2856. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2857. }
  2858. }
  2859. }
  2860. });
  2861. },
  2862. _initZoom: function () {
  2863. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  2864. modalMain = self._setTabIndex('modal', modalMain);
  2865. if (!self.showPreview) {
  2866. return;
  2867. }
  2868. self.$modal = $(modalId);
  2869. if (!self.$modal || !self.$modal.length) {
  2870. $dialog = $h.createElement($h.cspBuffer.stash(modalMain)).insertAfter(self.$container);
  2871. self.$modal = $(modalId).insertBefore($dialog);
  2872. $h.cspBuffer.apply(self.$modal);
  2873. $dialog.remove();
  2874. }
  2875. $h.initModal(self.$modal);
  2876. self.$modal.html($h.cspBuffer.stash(self._getModalContent()));
  2877. $h.cspBuffer.apply(self.$modal);
  2878. $.each($h.MODAL_EVENTS, function (key, event) {
  2879. self._listenModalEvent(event);
  2880. });
  2881. },
  2882. _initZoomButtons: function () {
  2883. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  2884. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-kv-prev'),
  2885. $next = self.$modal.find('.btn-kv-next');
  2886. if (thumbs.length < 2) {
  2887. $prev.hide();
  2888. $next.hide();
  2889. return;
  2890. } else {
  2891. $prev.show();
  2892. $next.show();
  2893. }
  2894. if (!len) {
  2895. return;
  2896. }
  2897. $first = $(thumbs[0]);
  2898. $last = $(thumbs[len - 1]);
  2899. $prev.removeAttr('disabled');
  2900. $next.removeAttr('disabled');
  2901. if (self.reversePreviewOrder) {
  2902. [$prev, $next] = [$next, $prev]; // swap
  2903. }
  2904. if ($first.length && $first.attr('id') === previewId) {
  2905. $prev.attr('disabled', true);
  2906. }
  2907. if ($last.length && $last.attr('id') === previewId) {
  2908. $next.attr('disabled', true);
  2909. }
  2910. },
  2911. _maximizeZoomDialog: function () {
  2912. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  2913. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.kv-zoom-body'),
  2914. h = $(window).height(), diff = 0;
  2915. $modal.addClass('file-zoom-fullscreen');
  2916. if ($head && $head.length) {
  2917. h -= $head.outerHeight(true);
  2918. }
  2919. if ($foot && $foot.length) {
  2920. h -= $foot.outerHeight(true);
  2921. }
  2922. if ($body && $body.length) {
  2923. diff = $body.outerHeight(true) - $body.height();
  2924. h -= diff;
  2925. }
  2926. $modal.find('.kv-zoom-body').height(h);
  2927. },
  2928. _resizeZoomDialog: function (fullScreen) {
  2929. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-kv-fullscreen'),
  2930. $btnBord = $modal.find('.btn-kv-borderless');
  2931. if ($modal.hasClass('file-zoom-fullscreen')) {
  2932. $h.toggleFullScreen(false);
  2933. if (!fullScreen) {
  2934. if (!$btnFull.hasClass('active')) {
  2935. $modal.removeClass('file-zoom-fullscreen');
  2936. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  2937. } else {
  2938. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2939. }
  2940. } else {
  2941. if (!$btnFull.hasClass('active')) {
  2942. $modal.removeClass('file-zoom-fullscreen');
  2943. self._resizeZoomDialog(true);
  2944. if ($btnBord.hasClass('active')) {
  2945. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2946. }
  2947. }
  2948. }
  2949. } else {
  2950. if (!fullScreen) {
  2951. self._maximizeZoomDialog();
  2952. return;
  2953. }
  2954. $h.toggleFullScreen(true);
  2955. }
  2956. $modal.focus();
  2957. },
  2958. _setZoomContent: function ($frame, navigate) {
  2959. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'),
  2960. $zoomPreview = self._getZoom(previewId), $modal = self.$modal, $tmp, desc, $desc,
  2961. $btnFull = $modal.find('.btn-kv-fullscreen'), $btnBord = $modal.find('.btn-kv-borderless'), cap, size,
  2962. $btnTogh = $modal.find('.btn-kv-toggleheader'), dir = navigate === 'prev' ? 'Left' : 'Right',
  2963. slideIn = 'slideIn' + dir, slideOut = 'slideOut' + dir, parsed, zoomData = $frame.data('zoom');
  2964. if (zoomData) {
  2965. zoomData = decodeURIComponent(zoomData);
  2966. parsed = $zoomPreview.html().replace($h.ZOOM_VAR, '').setTokens({zoomData: zoomData});
  2967. $zoomPreview.html(parsed);
  2968. $frame.data('zoom', '');
  2969. $zoomPreview.attr('data-zoom', zoomData);
  2970. }
  2971. tmplt = $zoomPreview.attr('data-template') || 'generic';
  2972. $content = $zoomPreview.find('.kv-file-content');
  2973. body = $content.length ? '<span class="kv-spacer"></span>\n' + $content.html() : '';
  2974. cap = $frame.data('caption') || self.msgZoomModalHeading;
  2975. size = $frame.data('size') || '';
  2976. desc = $frame.data('description') || '';
  2977. $modal.find('.kv-zoom-caption').attr('title', cap).html(cap);
  2978. $modal.find('.kv-zoom-size').html(size);
  2979. $desc = $modal.find('.kv-zoom-description').hide();
  2980. if (desc) {
  2981. if (self.showDescriptionClose) {
  2982. desc = self._getLayoutTemplate('descriptionClose').setTokens({
  2983. closeIcon: self.previewZoomButtonIcons.close
  2984. }) + '</button>' + desc;
  2985. }
  2986. $desc.show().html(desc);
  2987. if (self.showDescriptionClose) {
  2988. self._handler($modal.find('.kv-desc-hide'), 'click', function () {
  2989. $(this).parent().fadeOut('fast', function () {
  2990. $modal.focus();
  2991. });
  2992. });
  2993. }
  2994. }
  2995. $body = $modal.find('.kv-zoom-body');
  2996. $modal.removeClass('kv-single-content');
  2997. if (navigate) {
  2998. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  2999. $h.setHtml($body, body).hide();
  3000. $tmp.fadeOut('fast', function () {
  3001. $body.fadeIn('fast', function () {
  3002. $body.removeClass('file-thumb-loading');
  3003. });
  3004. $tmp.remove();
  3005. });
  3006. } else {
  3007. $h.setHtml($body, body);
  3008. }
  3009. config = self.previewZoomSettings[tmplt];
  3010. if (config) {
  3011. $dataEl = $body.find('.kv-preview-data');
  3012. $h.addCss($dataEl, 'file-zoom-detail');
  3013. $.each(config, function (key, value) {
  3014. $dataEl.css(key, value);
  3015. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  3016. $dataEl.removeAttr(key);
  3017. }
  3018. });
  3019. }
  3020. $modal.data('previewId', previewId);
  3021. self._handler($modal.find('.btn-kv-prev'), 'click', function () {
  3022. self._zoomSlideShow('prev', previewId);
  3023. });
  3024. self._handler($modal.find('.btn-kv-next'), 'click', function () {
  3025. self._zoomSlideShow('next', previewId);
  3026. });
  3027. self._handler($btnFull, 'click', function () {
  3028. self._resizeZoomDialog(true);
  3029. });
  3030. self._handler($btnBord, 'click', function () {
  3031. self._resizeZoomDialog(false);
  3032. });
  3033. self._handler($btnTogh, 'click', function () {
  3034. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.floating-buttons'),
  3035. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  3036. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  3037. if ($modal.hasClass('file-zoom-fullscreen')) {
  3038. h = $body.outerHeight(true);
  3039. if (!height) {
  3040. h = h - $header.outerHeight(true);
  3041. }
  3042. }
  3043. $body.css('height', height ? h + height : h);
  3044. };
  3045. if ($header.is(':visible')) {
  3046. ht = $header.outerHeight(true);
  3047. $header.slideUp('slow', function () {
  3048. $actions.find('.btn').appendTo($floatBar);
  3049. resize(ht);
  3050. });
  3051. } else {
  3052. $floatBar.find('.btn').appendTo($actions);
  3053. $header.slideDown('slow', function () {
  3054. resize();
  3055. });
  3056. }
  3057. $modal.focus();
  3058. });
  3059. self._handler($modal, 'keydown', function (e) {
  3060. var key = e.which || e.keyCode, delay = self.processDelay + 1, $prev = $(this).find('.btn-kv-prev'),
  3061. $next = $(this).find('.btn-kv-next'), vId = $(this).data('previewId'), vPrevKey, vNextKey;
  3062. [vPrevKey, vNextKey] = self.rtl ? [39, 37] : [37, 39];
  3063. $.each({prev: [$prev, vPrevKey], next: [$next, vNextKey]}, function (direction, config) {
  3064. var $btn = config[0], vKey = config[1];
  3065. if (key === vKey && $btn.length) {
  3066. $modal.focus();
  3067. if (!$btn.attr('disabled')) {
  3068. $btn.focus();
  3069. self._zoomSlideShow(direction, vId);
  3070. setTimeout(function () {
  3071. if ($btn.attr('disabled')) {
  3072. $modal.focus();
  3073. }
  3074. }, delay);
  3075. }
  3076. }
  3077. });
  3078. });
  3079. },
  3080. _showModal: function ($frame) {
  3081. var self = this, $modal = self.$modal, bs5Modal;
  3082. if (!$frame || !$frame.length) {
  3083. return;
  3084. }
  3085. $h.initModal($modal);
  3086. $h.setHtml($modal, self._getModalContent());
  3087. self._setZoomContent($frame);
  3088. $modal.data({backdrop: false});
  3089. //$modal.data('fileinputPluginId', self.$element.attr('id'));
  3090. $modal.modal('show');
  3091. self._initZoomButtons();
  3092. },
  3093. _zoomPreview: function ($btn) {
  3094. var self = this, $frame;
  3095. if (!$btn.length) {
  3096. throw 'Cannot zoom to detailed preview!';
  3097. }
  3098. $frame = $btn.closest($h.FRAMES);
  3099. self._showModal($frame);
  3100. },
  3101. _zoomSlideShow: function (dir, previewId) {
  3102. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-kv-' + dir), $targFrame, i, $thumb,
  3103. thumbsData = self.getFrames().toArray(), thumbs = [], len = thumbsData.length, out;
  3104. if (self.reversePreviewOrder) {
  3105. dir = dir === 'prev' ? 'next' : 'prev';
  3106. }
  3107. if ($btn.attr('disabled')) {
  3108. return;
  3109. }
  3110. for (i = 0; i < len; i++) {
  3111. $thumb = $(thumbsData[i]);
  3112. if ($thumb && $thumb.length && $thumb.find('.kv-file-zoom:visible').length) {
  3113. thumbs.push(thumbsData[i]);
  3114. }
  3115. }
  3116. len = thumbs.length;
  3117. for (i = 0; i < len; i++) {
  3118. if ($(thumbs[i]).attr('id') === previewId) {
  3119. out = dir === 'prev' ? i - 1 : i + 1;
  3120. break;
  3121. }
  3122. }
  3123. if (out < 0 || out >= len || !thumbs[out]) {
  3124. return;
  3125. }
  3126. $targFrame = $(thumbs[out]);
  3127. if ($targFrame.length) {
  3128. self._setZoomContent($targFrame, dir);
  3129. }
  3130. self._initZoomButtons();
  3131. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  3132. },
  3133. _initZoomButton: function () {
  3134. var self = this;
  3135. self.$preview.find('.kv-file-zoom').each(function () {
  3136. var $el = $(this);
  3137. self._handler($el, 'click', function () {
  3138. self._zoomPreview($el);
  3139. });
  3140. });
  3141. },
  3142. _inputFileCount: function () {
  3143. return this.$element[0].files.length;
  3144. },
  3145. _refreshPreview: function () {
  3146. var self = this, files;
  3147. if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) {
  3148. return;
  3149. }
  3150. if (self.isAjaxUpload) {
  3151. if (self.fileManager.count() > 0) {
  3152. files = $.extend(true, {}, self.getFileList());
  3153. self.fileManager.clear();
  3154. self._clearFileInput();
  3155. } else {
  3156. files = self.$element[0].files;
  3157. }
  3158. } else {
  3159. files = self.$element[0].files;
  3160. }
  3161. if (files && files.length) {
  3162. self.readFiles(files);
  3163. self._setFileDropZoneTitle();
  3164. }
  3165. },
  3166. _clearObjects: function ($el) {
  3167. $el.find('video audio').each(function () {
  3168. this.pause();
  3169. $(this).remove();
  3170. });
  3171. $el.find('img object div').each(function () {
  3172. $(this).remove();
  3173. });
  3174. },
  3175. _clearFileInput: function () {
  3176. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  3177. if (!self._inputFileCount()) {
  3178. return;
  3179. }
  3180. $srcFrm = $el.closest('form');
  3181. $tmpFrm = $(document.createElement('form'));
  3182. $tmpEl = $(document.createElement('div'));
  3183. $el.before($tmpEl);
  3184. if ($srcFrm.length) {
  3185. $srcFrm.after($tmpFrm);
  3186. } else {
  3187. $tmpEl.after($tmpFrm);
  3188. }
  3189. $tmpFrm.append($el).trigger('reset');
  3190. $tmpEl.before($el).remove();
  3191. $tmpFrm.remove();
  3192. },
  3193. _resetUpload: function () {
  3194. var self = this;
  3195. self.uploadStartTime = $h.now();
  3196. self.uploadCache = [];
  3197. self.$btnUpload.removeAttr('disabled');
  3198. self._setProgress(0);
  3199. self._hideProgress();
  3200. self._resetErrors(false);
  3201. self._initAjax();
  3202. self.fileManager.clearImages();
  3203. self._resetCanvas();
  3204. if (self.overwriteInitial) {
  3205. self.initialPreview = [];
  3206. self.initialPreviewConfig = [];
  3207. self.initialPreviewThumbTags = [];
  3208. self.previewCache.data = {
  3209. content: [],
  3210. config: [],
  3211. tags: []
  3212. };
  3213. }
  3214. },
  3215. _resetCanvas: function () {
  3216. var self = this;
  3217. if (self.imageCanvas && self.imageCanvasContext) {
  3218. self.imageCanvasContext.clearRect(0, 0, self.imageCanvas.width, self.imageCanvas.height);
  3219. }
  3220. },
  3221. _hasInitialPreview: function () {
  3222. var self = this;
  3223. return !self.overwriteInitial && self.previewCache.count(true);
  3224. },
  3225. _resetPreview: function () {
  3226. var self = this, out, cap, $div, hasSuc = self.showUploadedThumbs, hasErr = !self.removeFromPreviewOnError,
  3227. includeProcessed = (hasSuc || hasErr) && self.isDuplicateError;
  3228. if (self.previewCache.count(true)) {
  3229. out = self.previewCache.out();
  3230. if (includeProcessed) {
  3231. $div = $h.createElement('').insertAfter(self.$container);
  3232. self.getFrames().each(function () {
  3233. var $thumb = $(this);
  3234. if ((hasSuc && $thumb.hasClass('file-preview-success')) ||
  3235. (hasErr && $thumb.hasClass('file-preview-error'))) {
  3236. $div.append($thumb);
  3237. }
  3238. });
  3239. }
  3240. self._setPreviewContent(out.content);
  3241. self._setInitThumbAttr();
  3242. cap = self.initialCaption ? self.initialCaption : out.caption;
  3243. self._setCaption(cap);
  3244. if (includeProcessed) {
  3245. $div.contents().appendTo(self.$preview);
  3246. $div.remove();
  3247. }
  3248. } else {
  3249. self._clearPreview();
  3250. self._initCaption();
  3251. }
  3252. if (self.showPreview) {
  3253. self._initZoom();
  3254. self._initSortable();
  3255. }
  3256. self.isDuplicateError = false;
  3257. },
  3258. _clearDefaultPreview: function () {
  3259. var self = this;
  3260. self.$preview.find('.file-default-preview').remove();
  3261. },
  3262. _validateDefaultPreview: function () {
  3263. var self = this;
  3264. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  3265. return;
  3266. }
  3267. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  3268. self.$container.removeClass('file-input-new');
  3269. self._initClickable();
  3270. },
  3271. _resetPreviewThumbs: function (isAjax) {
  3272. var self = this, out;
  3273. if (isAjax) {
  3274. self._clearPreview();
  3275. self.clearFileStack();
  3276. return;
  3277. }
  3278. if (self._hasInitialPreview()) {
  3279. out = self.previewCache.out();
  3280. self._setPreviewContent(out.content);
  3281. self._setInitThumbAttr();
  3282. self._setCaption(out.caption);
  3283. self._initPreviewActions();
  3284. } else {
  3285. self._clearPreview();
  3286. }
  3287. },
  3288. _getLayoutTemplate: function (t) {
  3289. var self = this, template = self.layoutTemplates[t];
  3290. if ($h.isEmpty(self.customLayoutTags)) {
  3291. return template;
  3292. }
  3293. return $h.replaceTags(template, self.customLayoutTags);
  3294. },
  3295. _getPreviewTemplate: function (t) {
  3296. var self = this, templates = self.previewTemplates, template = templates[t] || templates.other;
  3297. if ($h.isEmpty(self.customPreviewTags)) {
  3298. return template;
  3299. }
  3300. return $h.replaceTags(template, self.customPreviewTags);
  3301. },
  3302. _getOutData: function (formdata, jqXHR, responseData, filesData) {
  3303. var self = this;
  3304. jqXHR = jqXHR || {};
  3305. responseData = responseData || {};
  3306. filesData = filesData || self.fileManager.list();
  3307. return {
  3308. formdata: formdata,
  3309. files: filesData,
  3310. filenames: self.filenames,
  3311. filescount: self.getFilesCount(),
  3312. extra: self._getExtraData(),
  3313. response: responseData,
  3314. reader: self.reader,
  3315. jqXHR: jqXHR
  3316. };
  3317. },
  3318. _getMsgSelected: function (n, processing) {
  3319. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  3320. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) :
  3321. (processing ? self.msgProcessing : self.msgNoFilesSelected);
  3322. },
  3323. _getFrame: function (id, skipWarning) {
  3324. var self = this, $frame = $h.getFrameElement(self.$preview, id);
  3325. if (self.showPreview && !skipWarning && !$frame.length) {
  3326. self._log($h.logMessages.invalidThumb, {id: id});
  3327. }
  3328. return $frame;
  3329. },
  3330. _getZoom: function (id, selector) {
  3331. var self = this, $frame = $h.getZoomElement(self.$preview, id, selector);
  3332. if (self.showPreview && !$frame.length) {
  3333. self._log($h.logMessages.invalidThumb, {id: id});
  3334. }
  3335. return $frame;
  3336. },
  3337. _getThumbs: function (css) {
  3338. css = css || '';
  3339. return this.getFrames(':not(.file-preview-initial)' + css);
  3340. },
  3341. _getThumbId: function (fileId) {
  3342. var self = this;
  3343. return self.previewInitId + '-' + fileId;
  3344. },
  3345. _getExtraData: function (fileId, index) {
  3346. var self = this, data = self.uploadExtraData;
  3347. if (typeof self.uploadExtraData === 'function') {
  3348. data = self.uploadExtraData(fileId, index);
  3349. }
  3350. return data;
  3351. },
  3352. _initXhr: function (xhrobj, fileId) {
  3353. var self = this, fm = self.fileManager, func = function (event) {
  3354. var pct = 0, total = event.total, loaded = event.loaded || event.position,
  3355. stats = fm.getUploadStats(fileId, loaded, total);
  3356. /** @namespace event.lengthComputable */
  3357. if (event.lengthComputable && !self.enableResumableUpload) {
  3358. pct = $h.round(loaded / total * 100);
  3359. }
  3360. if (fileId) {
  3361. self._setFileUploadStats(fileId, pct, stats);
  3362. } else {
  3363. self._setProgress(pct, null, null, self._getStats(stats));
  3364. }
  3365. self._raise('fileajaxprogress', [stats]);
  3366. };
  3367. if (xhrobj.upload) {
  3368. if (self.progressDelay) {
  3369. func = $h.debounce(func, self.progressDelay);
  3370. }
  3371. xhrobj.upload.addEventListener('progress', func, false);
  3372. }
  3373. return xhrobj;
  3374. },
  3375. _initAjaxSettings: function () {
  3376. var self = this;
  3377. self._ajaxSettings = $.extend(true, {}, self.ajaxSettings);
  3378. self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings);
  3379. },
  3380. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  3381. var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  3382. if (type === 'delete') {
  3383. settings = self._ajaxDeleteSettings;
  3384. flag = self.mergeAjaxDeleteCallbacks;
  3385. }
  3386. targFunc = settings[funcName];
  3387. if (flag && typeof targFunc === 'function') {
  3388. if (flag === 'before') {
  3389. settings[funcName] = function () {
  3390. targFunc.apply(this, arguments);
  3391. srcFunc.apply(this, arguments);
  3392. };
  3393. } else {
  3394. settings[funcName] = function () {
  3395. srcFunc.apply(this, arguments);
  3396. targFunc.apply(this, arguments);
  3397. };
  3398. }
  3399. } else {
  3400. settings[funcName] = srcFunc;
  3401. }
  3402. },
  3403. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) {
  3404. var self = this, settings, defaults, data, ajaxTask;
  3405. if (!self._raise('filepreajax', [formdata, fileId, index])) {
  3406. return;
  3407. }
  3408. formdata.append('initialPreview', JSON.stringify(self.initialPreview));
  3409. formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig));
  3410. formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags));
  3411. self._initAjaxSettings();
  3412. self._mergeAjaxCallback('beforeSend', fnBefore);
  3413. self._mergeAjaxCallback('success', fnSuccess);
  3414. self._mergeAjaxCallback('complete', fnComplete);
  3415. self._mergeAjaxCallback('error', fnError);
  3416. vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl;
  3417. if (typeof vUrl === 'function') {
  3418. vUrl = vUrl();
  3419. }
  3420. data = self._getExtraData(fileId, index) || {};
  3421. if (typeof data === 'object') {
  3422. $.each(data, function (key, value) {
  3423. formdata.append(key, value);
  3424. });
  3425. }
  3426. defaults = {
  3427. xhr: function () {
  3428. var xhrobj = $.ajaxSettings.xhr();
  3429. return self._initXhr(xhrobj, fileId);
  3430. },
  3431. url: self._encodeURI(vUrl),
  3432. type: 'POST',
  3433. dataType: 'json',
  3434. data: formdata,
  3435. cache: false,
  3436. processData: false,
  3437. contentType: false
  3438. };
  3439. settings = $.extend(true, {}, defaults, self._ajaxSettings);
  3440. ajaxTask = self.taskManager.addTask(fileId + '-' + index, function () {
  3441. var self = this.self, config, xhr;
  3442. config = self.ajaxQueue.shift();
  3443. xhr = $.ajax(config);
  3444. self.ajaxRequests.push(xhr);
  3445. });
  3446. self.ajaxQueue.push(settings);
  3447. ajaxTask.runWithContext({self: self});
  3448. },
  3449. _mergeArray: function (prop, content) {
  3450. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  3451. self[prop] = arr1.concat(arr2);
  3452. },
  3453. _initUploadSuccess: function (out, $thumb, allFiles) {
  3454. var self = this, append, data, index, $div, content, config, tags, id, i;
  3455. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  3456. self._resetCaption();
  3457. return;
  3458. }
  3459. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  3460. self.hasInitData = true;
  3461. content = out.initialPreview || [];
  3462. config = out.initialPreviewConfig || [];
  3463. tags = out.initialPreviewThumbTags || [];
  3464. append = out.append === undefined || out.append;
  3465. if (content.length > 0 && !$h.isArray(content)) {
  3466. content = content.split(self.initialPreviewDelimiter);
  3467. }
  3468. if (content.length) {
  3469. self._mergeArray('initialPreview', content);
  3470. self._mergeArray('initialPreviewConfig', config);
  3471. self._mergeArray('initialPreviewThumbTags', tags);
  3472. }
  3473. if ($thumb !== undefined) {
  3474. if (!allFiles) {
  3475. index = self.previewCache.add(content[0], config[0], tags[0], append);
  3476. data = self.previewCache.get(index, false);
  3477. $div = $h.createElement(data).hide().appendTo($thumb);
  3478. $thumb.fadeOut('slow', function () {
  3479. var $newThumb = $div.find('> .file-preview-frame');
  3480. if ($newThumb && $newThumb.length) {
  3481. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  3482. }
  3483. self._initPreviewActions();
  3484. self._clearFileInput();
  3485. $thumb.remove();
  3486. $div.remove();
  3487. self._initSortable();
  3488. });
  3489. } else {
  3490. id = $thumb.attr('id');
  3491. i = self._getUploadCacheIndex(id);
  3492. if (i !== null) {
  3493. self.uploadCache[i] = {
  3494. id: id,
  3495. content: content[0],
  3496. config: config[0] || [],
  3497. tags: tags[0] || [],
  3498. append: append
  3499. };
  3500. }
  3501. }
  3502. } else {
  3503. self.previewCache.set(content, config, tags, append);
  3504. self._initPreview();
  3505. self._initPreviewActions();
  3506. }
  3507. }
  3508. self._resetCaption();
  3509. },
  3510. _getUploadCacheIndex: function (id) {
  3511. var self = this, i, len = self.uploadCache.length, config;
  3512. for (i = 0; i < len; i++) {
  3513. config = self.uploadCache[i];
  3514. if (config.id === id) {
  3515. return i;
  3516. }
  3517. }
  3518. return null;
  3519. },
  3520. _initSuccessThumbs: function () {
  3521. var self = this;
  3522. if (!self.showPreview) {
  3523. return;
  3524. }
  3525. setTimeout(function () {
  3526. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  3527. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  3528. $remove.removeAttr('disabled');
  3529. self._handler($remove, 'click', function () {
  3530. var id = $thumb.attr('id'),
  3531. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  3532. $h.cleanMemory($thumb);
  3533. if (out === false) {
  3534. return;
  3535. }
  3536. self.$caption.attr('title', '');
  3537. $thumb.fadeOut('slow', function () {
  3538. var fm = self.fileManager;
  3539. $thumb.remove();
  3540. if (!self.getFrames().length) {
  3541. self.reset();
  3542. }
  3543. });
  3544. });
  3545. });
  3546. }, self.processDelay);
  3547. },
  3548. _updateInitialPreview: function () {
  3549. var self = this, u = self.uploadCache;
  3550. if (self.showPreview) {
  3551. $.each(u, function (key, setting) {
  3552. self.previewCache.add(setting.content, setting.config, setting.tags, setting.append);
  3553. });
  3554. if (self.hasInitData) {
  3555. self._initPreview();
  3556. self._initPreviewActions();
  3557. }
  3558. }
  3559. },
  3560. _getThumbFileId: function ($thumb) {
  3561. var self = this;
  3562. if (self.showPreview && $thumb !== undefined) {
  3563. return $thumb.attr('data-fileid');
  3564. }
  3565. return null;
  3566. },
  3567. _getThumbFile: function ($thumb) {
  3568. var self = this, id = self._getThumbFileId($thumb);
  3569. return id ? self.fileManager.getFile(id) : null;
  3570. },
  3571. _uploadSingle: function (i, id, isBatch) {
  3572. var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData,
  3573. previewId = self._getThumbId(id), $thumb, chkComplete, $btnUpload, $btnDelete,
  3574. hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore,
  3575. errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb,
  3576. fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id},
  3577. fileName = self.fileManager.getFileName(id, true);
  3578. if (self.enableResumableUpload) { // not enabled for resumable uploads
  3579. return;
  3580. }
  3581. if (self.showPreview) {
  3582. $thumb = fm.getThumb(id);
  3583. $prog = $thumb.find('.file-thumb-progress');
  3584. $btnUpload = $thumb.find('.kv-file-upload');
  3585. $btnDelete = $thumb.find('.kv-file-remove');
  3586. $prog.show();
  3587. }
  3588. if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) ||
  3589. self._abort(params)) {
  3590. return;
  3591. }
  3592. updateUploadLog = function () {
  3593. if (!uploadFailed) {
  3594. fm.removeFile(id);
  3595. } else {
  3596. fm.errors.push(id);
  3597. }
  3598. fm.setProcessed(id);
  3599. if (fm.isProcessed()) {
  3600. self.fileBatchCompleted = true;
  3601. chkComplete();
  3602. }
  3603. };
  3604. chkComplete = function () {
  3605. var $initThumbs;
  3606. if (!self.fileBatchCompleted) {
  3607. return;
  3608. }
  3609. setTimeout(function () {
  3610. var triggerReset = fm.count() === 0, errCount = fm.errors.length;
  3611. self._updateInitialPreview();
  3612. self.unlock(triggerReset);
  3613. if (triggerReset) {
  3614. self._clearFileInput();
  3615. }
  3616. $initThumbs = self.$preview.find('.file-preview-initial');
  3617. if (self.uploadAsync && $initThumbs.length) {
  3618. $h.addCss($initThumbs, $h.SORT_CSS);
  3619. self._initSortable();
  3620. }
  3621. self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]);
  3622. if (!self.retryErrorUploads || errCount === 0) {
  3623. fm.clear();
  3624. }
  3625. self._setProgress(101);
  3626. self.ajaxAborted = false;
  3627. }, self.processDelay);
  3628. };
  3629. fnBefore = function (jqXHR) {
  3630. outData = self._getOutData(formdata, jqXHR);
  3631. fm.initStats(id);
  3632. self.fileBatchCompleted = false;
  3633. if (!isBatch) {
  3634. self.ajaxAborted = false;
  3635. }
  3636. if (self.showPreview) {
  3637. if (!$thumb.hasClass('file-preview-success')) {
  3638. self._setThumbStatus($thumb, 'Loading');
  3639. $h.addCss($thumb, 'file-uploading');
  3640. }
  3641. $btnUpload.attr('disabled', true);
  3642. $btnDelete.attr('disabled', true);
  3643. }
  3644. if (!isBatch) {
  3645. self.lock();
  3646. }
  3647. if (fm.errors.indexOf(id) !== -1) {
  3648. delete fm.errors[id];
  3649. }
  3650. self._raise('filepreupload', [outData, previewId, i, self._getThumbFileId($thumb)]);
  3651. $.extend(true, params, outData);
  3652. if (self._abort(params)) {
  3653. jqXHR.abort();
  3654. if (!isBatch) {
  3655. self._setThumbStatus($thumb, 'New');
  3656. $thumb.removeClass('file-uploading');
  3657. $btnUpload.removeAttr('disabled');
  3658. $btnDelete.removeAttr('disabled');
  3659. }
  3660. self._setProgressCancelled();
  3661. }
  3662. };
  3663. fnSuccess = function (data, textStatus, jqXHR) {
  3664. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  3665. outData = self._getOutData(formdata, jqXHR, data);
  3666. $.extend(true, params, outData);
  3667. setTimeout(function () {
  3668. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3669. if (self.showPreview) {
  3670. self._setThumbStatus($thumb, 'Success');
  3671. $btnUpload.hide();
  3672. self._initUploadSuccess(data, $thumb, isBatch);
  3673. self._setProgress(101, $prog);
  3674. }
  3675. self._raise('fileuploaded', [outData, pid, i, self._getThumbFileId($thumb)]);
  3676. if (!isBatch) {
  3677. self.fileManager.remove($thumb);
  3678. } else {
  3679. updateUploadLog();
  3680. }
  3681. } else {
  3682. uploadFailed = true;
  3683. errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id));
  3684. self._showFileError(errMsg, params);
  3685. self._setPreviewError($thumb, true);
  3686. if (!self.retryErrorUploads) {
  3687. $btnUpload.hide();
  3688. }
  3689. if (isBatch) {
  3690. updateUploadLog();
  3691. }
  3692. self._setProgress(101, self._getFrame(pid).find('.file-thumb-progress'),
  3693. self.msgUploadError);
  3694. }
  3695. }, self.processDelay);
  3696. };
  3697. fnComplete = function () {
  3698. if (self.showPreview) {
  3699. $btnUpload.removeAttr('disabled');
  3700. $btnDelete.removeAttr('disabled');
  3701. $thumb.removeClass('file-uploading');
  3702. }
  3703. if (!isBatch) {
  3704. self.unlock(false);
  3705. self._clearFileInput();
  3706. } else {
  3707. chkComplete();
  3708. }
  3709. self._initSuccessThumbs();
  3710. };
  3711. fnError = function (jqXHR, textStatus, errorThrown) {
  3712. errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id));
  3713. uploadFailed = true;
  3714. setTimeout(function () {
  3715. var $prog;
  3716. if (isBatch) {
  3717. updateUploadLog();
  3718. }
  3719. self.fileManager.setProgress(id, 100);
  3720. self._setPreviewError($thumb, true);
  3721. if (!self.retryErrorUploads) {
  3722. $btnUpload.hide();
  3723. }
  3724. $.extend(true, params, self._getOutData(formdata, jqXHR));
  3725. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3726. $prog = self.showPreview && $thumb ? $thumb.find('.file-thumb-progress') : '';
  3727. self._setProgress(101, $prog, self.msgUploadError);
  3728. self._showFileError(errMsg, params);
  3729. }, self.processDelay);
  3730. };
  3731. self._setFileData(formdata, fileObj.file, fileName, id);
  3732. self._setUploadData(formdata, {fileId: id});
  3733. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i);
  3734. },
  3735. _setFileData: function (formdata, file, fileName, fileId) {
  3736. var self = this, preProcess = self.preProcessUpload;
  3737. if (preProcess && typeof preProcess === 'function') {
  3738. formdata.append(self.uploadFileAttr, preProcess(fileId, file));
  3739. } else {
  3740. formdata.append(self.uploadFileAttr, file, fileName);
  3741. }
  3742. },
  3743. _checkBatchPreupload: function (outData, jqXHR) {
  3744. var self = this, out = self._raise('filebatchpreupload', [outData]);
  3745. if (out) {
  3746. return true;
  3747. }
  3748. self._abort(outData);
  3749. if (jqXHR) {
  3750. jqXHR.abort();
  3751. }
  3752. self._getThumbs().each(function () {
  3753. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3754. $btnDelete = $thumb.find('.kv-file-remove');
  3755. if ($thumb.hasClass('file-preview-loading')) {
  3756. self._setThumbStatus($thumb, 'New');
  3757. $thumb.removeClass('file-uploading');
  3758. }
  3759. $btnUpload.removeAttr('disabled');
  3760. $btnDelete.removeAttr('disabled');
  3761. });
  3762. self._setProgressCancelled();
  3763. return false;
  3764. },
  3765. _uploadBatch: function () {
  3766. var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError,
  3767. fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg,
  3768. setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch;
  3769. if (total === 0 || !hasPostData || self._abort(params)) {
  3770. return;
  3771. }
  3772. setAllUploaded = function () {
  3773. self.fileManager.clear();
  3774. self._clearFileInput();
  3775. };
  3776. fnBefore = function (jqXHR) {
  3777. self.lock();
  3778. fm.initStats();
  3779. var outData = self._getOutData(formdata, jqXHR);
  3780. self.ajaxAborted = false;
  3781. if (self.showPreview) {
  3782. self._getThumbs().each(function () {
  3783. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3784. $btnDelete = $thumb.find('.kv-file-remove');
  3785. if (!$thumb.hasClass('file-preview-success')) {
  3786. self._setThumbStatus($thumb, 'Loading');
  3787. $h.addCss($thumb, 'file-uploading');
  3788. }
  3789. $btnUpload.attr('disabled', true);
  3790. $btnDelete.attr('disabled', true);
  3791. });
  3792. }
  3793. self._checkBatchPreupload(outData, jqXHR);
  3794. };
  3795. fnSuccess = function (data, textStatus, jqXHR) {
  3796. /** @namespace data.errorkeys */
  3797. var outData = self._getOutData(formdata, jqXHR, data), key = 0,
  3798. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  3799. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  3800. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3801. self._raise('filebatchuploadsuccess', [outData]);
  3802. setAllUploaded();
  3803. if (self.showPreview) {
  3804. $thumbs.each(function () {
  3805. var $thumb = $(this);
  3806. self._setThumbStatus($thumb, 'Success');
  3807. $thumb.removeClass('file-uploading');
  3808. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  3809. });
  3810. self._initUploadSuccess(data);
  3811. } else {
  3812. self.reset();
  3813. }
  3814. self._setProgress(101);
  3815. } else {
  3816. if (self.showPreview) {
  3817. $thumbs.each(function () {
  3818. var $thumb = $(this);
  3819. $thumb.removeClass('file-uploading');
  3820. $thumb.find('.kv-file-upload').removeAttr('disabled');
  3821. $thumb.find('.kv-file-remove').removeAttr('disabled');
  3822. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  3823. self._setPreviewError($thumb, true);
  3824. if (!self.retryErrorUploads) {
  3825. $thumb.find('.kv-file-upload').hide();
  3826. self.fileManager.remove($thumb);
  3827. }
  3828. } else {
  3829. $thumb.find('.kv-file-upload').hide();
  3830. self._setThumbStatus($thumb, 'Success');
  3831. self.fileManager.remove($thumb);
  3832. }
  3833. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  3834. key++;
  3835. }
  3836. });
  3837. self._initUploadSuccess(data);
  3838. }
  3839. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3840. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3841. self._setProgress(101, self.$progress, self.msgUploadError);
  3842. }
  3843. };
  3844. fnComplete = function () {
  3845. self.unlock();
  3846. self._initSuccessThumbs();
  3847. self._clearFileInput();
  3848. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3849. };
  3850. fnError = function (jqXHR, textStatus, errorThrown) {
  3851. var outData = self._getOutData(formdata, jqXHR);
  3852. errMsg = self._parseError(op, jqXHR, errorThrown);
  3853. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3854. self.uploadFileCount = total - 1;
  3855. if (!self.showPreview) {
  3856. return;
  3857. }
  3858. self._getThumbs().each(function () {
  3859. var $thumb = $(this);
  3860. $thumb.removeClass('file-uploading');
  3861. if (self._getThumbFile($thumb)) {
  3862. self._setPreviewError($thumb);
  3863. }
  3864. });
  3865. self._getThumbs().removeClass('file-uploading');
  3866. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  3867. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  3868. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3869. };
  3870. var ctr = 0;
  3871. $.each(self.fileManager.stack, function (key, data) {
  3872. if (!$h.isEmpty(data.file)) {
  3873. self._setFileData(formdata, data.file, (data.nameFmt || ('untitled_' + ctr)), key);
  3874. }
  3875. ctr++;
  3876. });
  3877. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3878. },
  3879. _uploadExtraOnly: function () {
  3880. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg,
  3881. op = self.ajaxOperations.uploadExtra;
  3882. fnBefore = function (jqXHR) {
  3883. self.lock();
  3884. var outData = self._getOutData(formdata, jqXHR);
  3885. self._setProgress(50);
  3886. params.data = outData;
  3887. params.xhr = jqXHR;
  3888. self._checkBatchPreupload(outData, jqXHR);
  3889. };
  3890. fnSuccess = function (data, textStatus, jqXHR) {
  3891. var outData = self._getOutData(formdata, jqXHR, data);
  3892. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3893. self._raise('filebatchuploadsuccess', [outData]);
  3894. self._clearFileInput();
  3895. self._initUploadSuccess(data);
  3896. self._setProgress(101);
  3897. } else {
  3898. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3899. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3900. }
  3901. };
  3902. fnComplete = function () {
  3903. self.unlock();
  3904. self._clearFileInput();
  3905. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3906. };
  3907. fnError = function (jqXHR, textStatus, errorThrown) {
  3908. var outData = self._getOutData(formdata, jqXHR);
  3909. errMsg = self._parseError(op, jqXHR, errorThrown);
  3910. params.data = outData;
  3911. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3912. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3913. };
  3914. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3915. },
  3916. _deleteFileIndex: function ($frame) {
  3917. var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder;
  3918. if (ind.substring(0, 5) === $h.INIT_FLAG) {
  3919. ind = parseInt(ind.replace($h.INIT_FLAG, ''));
  3920. self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev);
  3921. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev);
  3922. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev);
  3923. self.getFrames().each(function () {
  3924. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  3925. if (nInd.substring(0, 5) === $h.INIT_FLAG) {
  3926. nInd = parseInt(nInd.replace($h.INIT_FLAG, ''));
  3927. if (nInd > ind) {
  3928. nInd--;
  3929. $nFrame.attr('data-fileindex', $h.INIT_FLAG + nInd);
  3930. }
  3931. }
  3932. });
  3933. }
  3934. },
  3935. _resetCaption: function () {
  3936. var self = this;
  3937. setTimeout(function () {
  3938. var cap = '', n, chk = self.previewCache.count(true), len = self.fileManager.count(), file,
  3939. incomplete = ':not(.file-preview-success):not(.file-preview-error)', cfg,
  3940. hasThumb = self.showPreview && self.getFrames(incomplete).length;
  3941. if (len === 0 && chk === 0 && !hasThumb) {
  3942. self.reset();
  3943. } else {
  3944. n = chk + len;
  3945. if (n > 1) {
  3946. cap = self._getMsgSelected(n);
  3947. } else {
  3948. if (len === 0) {
  3949. cfg = self.initialPreviewConfig[0];
  3950. cap = '';
  3951. if (cfg) {
  3952. cap = cfg.caption || cfg.filename || ''
  3953. }
  3954. if (!cap) {
  3955. cap = self._getMsgSelected(n);
  3956. }
  3957. } else {
  3958. file = self.fileManager.getFirstFile();
  3959. cap = file ? file.nameFmt : '_';
  3960. }
  3961. }
  3962. self._setCaption(cap);
  3963. }
  3964. }, self.processDelay);
  3965. },
  3966. _initFileActions: function () {
  3967. var self = this;
  3968. if (!self.showPreview) {
  3969. return;
  3970. }
  3971. self._initZoomButton();
  3972. self.getFrames(' .kv-file-remove').each(function () {
  3973. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  3974. ind = $frame.attr('data-fileindex'), status, fm = self.fileManager;
  3975. self._handler($el, 'click', function () {
  3976. status = self._raise('filepreremove', [id, ind]);
  3977. if (status === false || !self._validateMinCount()) {
  3978. return false;
  3979. }
  3980. hasError = $frame.hasClass('file-preview-error');
  3981. $h.cleanMemory($frame);
  3982. $frame.fadeOut('slow', function () {
  3983. self.fileManager.remove($frame);
  3984. self._clearObjects($frame);
  3985. $frame.remove();
  3986. if (id && hasError) {
  3987. self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () {
  3988. $(this).remove();
  3989. if (!self._errorsExist()) {
  3990. self._resetErrors();
  3991. }
  3992. });
  3993. }
  3994. self._clearFileInput();
  3995. self._resetCaption();
  3996. self._raise('fileremoved', [id, ind]);
  3997. });
  3998. });
  3999. });
  4000. self.getFrames(' .kv-file-upload').each(function () {
  4001. var $el = $(this);
  4002. self._handler($el, 'click', function () {
  4003. var $frame = $el.closest($h.FRAMES), fileId = self._getThumbFileId($frame);
  4004. self._hideProgress();
  4005. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  4006. return;
  4007. }
  4008. self._uploadSingle(self.fileManager.getIndex(fileId), fileId, false);
  4009. });
  4010. });
  4011. },
  4012. _initPreviewActions: function () {
  4013. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  4014. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  4015. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  4016. resetProgress = function () {
  4017. var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount();
  4018. if (!self.getFrames().length && !hasFiles) {
  4019. self._setCaption('');
  4020. self.reset();
  4021. self.initialCaption = '';
  4022. } else {
  4023. self._resetCaption();
  4024. }
  4025. };
  4026. self._initZoomButton();
  4027. $preview.find(btnRemove).each(function () {
  4028. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore,
  4029. fnSuccess, fnError, op = self.ajaxOperations.deleteThumb;
  4030. if ($h.isEmpty(vUrl) || vKey === undefined) {
  4031. return;
  4032. }
  4033. if (typeof vUrl === 'function') {
  4034. vUrl = vUrl();
  4035. }
  4036. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config,
  4037. fileName, extraData, index = $frame.attr('data-fileindex');
  4038. index = parseInt(index.replace($h.INIT_FLAG, ''));
  4039. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  4040. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  4041. fileName = config && (config.filename || config.caption) || '';
  4042. if (typeof extraData === 'function') {
  4043. extraData = extraData();
  4044. }
  4045. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  4046. fnBefore = function (jqXHR) {
  4047. self.ajaxAborted = false;
  4048. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  4049. if (self._abort()) {
  4050. jqXHR.abort();
  4051. } else {
  4052. $el.removeClass(errClass);
  4053. $h.addCss($frame, 'file-uploading');
  4054. $h.addCss($el, 'disabled ' + origClass);
  4055. }
  4056. };
  4057. fnSuccess = function (data, textStatus, jqXHR) {
  4058. var n, cap;
  4059. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  4060. params.jqXHR = jqXHR;
  4061. params.response = data;
  4062. errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName);
  4063. self._showFileError(errMsg, params, 'filedeleteerror');
  4064. $frame.removeClass('file-uploading');
  4065. $el.removeClass('disabled ' + origClass).addClass(errClass);
  4066. resetProgress();
  4067. return;
  4068. }
  4069. $frame.removeClass('file-uploading').addClass('file-deleted');
  4070. $frame.fadeOut('slow', function () {
  4071. index = parseInt(($frame.attr('data-fileindex')).replace($h.INIT_FLAG, ''));
  4072. self.previewCache.unset(index);
  4073. self._deleteFileIndex($frame);
  4074. n = self.previewCache.count(true);
  4075. cap = n > 0 ? self._getMsgSelected(n) : '';
  4076. self._setCaption(cap);
  4077. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  4078. self._clearObjects($frame);
  4079. $frame.remove();
  4080. resetProgress();
  4081. });
  4082. };
  4083. fnError = function (jqXHR, textStatus, errorThrown) {
  4084. var errMsg = self._parseError(op, jqXHR, errorThrown, fileName);
  4085. params.jqXHR = jqXHR;
  4086. params.response = {};
  4087. self._showFileError(errMsg, params, 'filedeleteerror');
  4088. $frame.removeClass('file-uploading');
  4089. $el.removeClass('disabled ' + origClass).addClass(errClass);
  4090. resetProgress();
  4091. };
  4092. self._initAjaxSettings();
  4093. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  4094. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  4095. self._mergeAjaxCallback('error', fnError, 'delete');
  4096. settings = $.extend(true, {}, {
  4097. url: self._encodeURI(vUrl),
  4098. type: 'POST',
  4099. dataType: 'json',
  4100. data: $.extend(true, {}, {key: vKey}, extraData)
  4101. }, self._ajaxDeleteSettings);
  4102. self._handler($el, 'click', function () {
  4103. if (!self._validateMinCount()) {
  4104. return false;
  4105. }
  4106. self.ajaxAborted = false;
  4107. self._raise('filebeforedelete', [vKey, extraData]);
  4108. if (self.ajaxAborted instanceof Promise) {
  4109. self.ajaxAborted.then(function (result) {
  4110. if (!result) {
  4111. $.ajax(settings);
  4112. }
  4113. });
  4114. } else {
  4115. if (!self.ajaxAborted) {
  4116. $.ajax(settings);
  4117. }
  4118. }
  4119. });
  4120. });
  4121. },
  4122. _hideFileIcon: function () {
  4123. var self = this;
  4124. if (self.overwriteInitial) {
  4125. self.$captionContainer.removeClass('icon-visible');
  4126. }
  4127. },
  4128. _showFileIcon: function () {
  4129. var self = this;
  4130. $h.addCss(self.$captionContainer, 'icon-visible');
  4131. },
  4132. _getSize: function (bytes, sizes) {
  4133. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out;
  4134. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  4135. return '';
  4136. }
  4137. if (typeof func === 'function') {
  4138. out = func(size);
  4139. } else {
  4140. if (size === 0) {
  4141. out = '0.00 B';
  4142. } else {
  4143. if (!sizes) {
  4144. sizes = self.sizeUnits;
  4145. }
  4146. i = Math.floor(Math.log(size) / Math.log(self.bytesToKB));
  4147. out = (size / Math.pow(self.bytesToKB, i)).toFixed(2) + ' ' + sizes[i];
  4148. }
  4149. }
  4150. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  4151. },
  4152. _getFileType: function (ftype) {
  4153. var self = this;
  4154. return self.mimeTypeAliases[ftype] || ftype;
  4155. },
  4156. _generatePreviewTemplate: function (
  4157. cat,
  4158. data,
  4159. fname,
  4160. ftype,
  4161. previewId,
  4162. fileId,
  4163. isError,
  4164. size,
  4165. frameClass,
  4166. foot,
  4167. ind,
  4168. templ,
  4169. attrs,
  4170. zoomData
  4171. ) {
  4172. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  4173. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  4174. config, title = caption, alt = caption, typeCss = 'type-default', getContent,
  4175. footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError),
  4176. forcePrevIcon = self.preferIconicPreview, forceZoomIcon = self.preferIconicZoomPreview,
  4177. newCat = forcePrevIcon ? 'other' : cat;
  4178. config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) :
  4179. (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]);
  4180. if (config) {
  4181. $.each(config, function (key, val) {
  4182. styleAttribs += key + ':' + val + ';';
  4183. });
  4184. }
  4185. getContent = function (vCat, vData, zoom, frameCss, vZoomData) {
  4186. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(vCat),
  4187. css = (frameClass || '') + ' ' + frameCss, tokens;
  4188. if (self.frameClass) {
  4189. css = self.frameClass + ' ' + css;
  4190. }
  4191. if (zoom) {
  4192. css = css.replace(' ' + $h.SORT_CSS, '');
  4193. }
  4194. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  4195. if (cat === 'object' && !ftype) {
  4196. $.each(self.defaults.fileTypeSettings, function (key, func) {
  4197. if (key === 'object' || key === 'other') {
  4198. return;
  4199. }
  4200. if (func(fname, ftype)) {
  4201. typeCss = 'type-' + key;
  4202. }
  4203. });
  4204. }
  4205. if (!$h.isEmpty(attrs)) {
  4206. if (attrs.title !== undefined && attrs.title !== null) {
  4207. title = attrs.title;
  4208. }
  4209. if (attrs.alt !== undefined && attrs.alt !== null) {
  4210. title = attrs.alt;
  4211. }
  4212. }
  4213. tokens = {
  4214. 'previewId': id,
  4215. 'caption': caption,
  4216. 'title': title,
  4217. 'alt': alt,
  4218. 'frameClass': css,
  4219. 'type': self._getFileType(ftype),
  4220. 'fileindex': ind,
  4221. 'fileid': fileId || '',
  4222. 'typeCss': typeCss,
  4223. 'footer': footer,
  4224. 'data': vData,
  4225. // 'data': zoom && vZoomData ? $h.ZOOM_VAR + '{zoomData}' : vData,
  4226. 'template': templ || cat,
  4227. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '',
  4228. 'zoomData': vZoomData ? encodeURIComponent(vZoomData) : ''
  4229. };
  4230. if (zoom) {
  4231. tokens.zoomCache = '';
  4232. tokens.zoomData = '{zoomData}';
  4233. }
  4234. return tmplt.setTokens(tokens);
  4235. };
  4236. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  4237. if (self.fileActionSettings.showZoom) {
  4238. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb', zoomData);
  4239. }
  4240. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  4241. if (typeof self.sanitizeZoomCache === 'function') {
  4242. zoomContent = self.sanitizeZoomCache(zoomContent);
  4243. }
  4244. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb', zoomData);
  4245. return prevContent.setTokens({zoomCache: zoomContent});
  4246. },
  4247. _addToPreview: function ($preview, content) {
  4248. var self = this, $el;
  4249. content = $h.cspBuffer.stash(content);
  4250. $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
  4251. $h.cspBuffer.apply($preview);
  4252. return $el;
  4253. },
  4254. _previewDefault: function (file, isDisabled) {
  4255. var self = this, $preview = self.$preview;
  4256. if (!self.showPreview) {
  4257. return;
  4258. }
  4259. var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0,
  4260. caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload,
  4261. data = $h.createObjectURL(file), fileId = self.fileManager.getId(file),
  4262. previewId = self._getThumbId(fileId);
  4263. self._clearDefaultPreview();
  4264. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size);
  4265. self._addToPreview($preview, content);
  4266. self._setThumbAttr(previewId, caption, size);
  4267. if (isDisabled === true && self.isAjaxUpload) {
  4268. self._setThumbStatus(self._getFrame(previewId), 'Error');
  4269. }
  4270. },
  4271. _previewFile: function (i, file, theFile, data, fileInfo) {
  4272. if (!this.showPreview) {
  4273. return;
  4274. }
  4275. var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name,
  4276. cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0,
  4277. iData = cat === 'image' ? theFile.target.result : data, fm = self.fileManager,
  4278. fileId = fm.getId(file), previewId = self._getThumbId(fileId);
  4279. /** @namespace window.DOMPurify */
  4280. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize);
  4281. self._clearDefaultPreview();
  4282. self._addToPreview($preview, content);
  4283. var $thumb = self._getFrame(previewId);
  4284. self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData);
  4285. self._setThumbAttr(previewId, caption, fsize);
  4286. self._initSortable();
  4287. },
  4288. _setThumbAttr: function (id, caption, size, description) {
  4289. var self = this, $frame = self._getFrame(id);
  4290. if ($frame.length) {
  4291. size = size && size > 0 ? self._getSize(size) : '';
  4292. $frame.data({'caption': caption, 'size': size, 'description': description || ''});
  4293. }
  4294. },
  4295. _setInitThumbAttr: function () {
  4296. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  4297. caption, size, description, previewId;
  4298. if (len === 0) {
  4299. return;
  4300. }
  4301. for (var i = 0; i < len; i++) {
  4302. config = data.config[i];
  4303. previewId = self.previewInitId + '-' + $h.INIT_FLAG + i;
  4304. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  4305. size = $h.ifSet('size', config);
  4306. description = $h.ifSet('description', config);
  4307. self._setThumbAttr(previewId, caption, size, description);
  4308. }
  4309. },
  4310. _slugDefault: function (text) {
  4311. // noinspection RegExpRedundantEscape
  4312. return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  4313. },
  4314. _updateFileDetails: function (numFiles) {
  4315. var self = this, $el = self.$element, label, n, log, nFiles, file,
  4316. name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name);
  4317. if (!name && self.fileManager.count() > 0) {
  4318. file = self.fileManager.getFirstFile();
  4319. label = file.nameFmt;
  4320. } else {
  4321. label = name ? self.slug(name) : '_';
  4322. }
  4323. n = self.isAjaxUpload ? self.fileManager.count() : numFiles;
  4324. nFiles = self.previewCache.count(true) + n;
  4325. log = n === 1 ? label : self._getMsgSelected(nFiles, !self.isAjaxUpload && !self.isError);
  4326. if (self.isError) {
  4327. self.$previewContainer.removeClass('file-thumb-loading');
  4328. self._initCapStatus();
  4329. self.$previewStatus.html('');
  4330. self.$captionContainer.removeClass('icon-visible');
  4331. } else {
  4332. self._showFileIcon();
  4333. }
  4334. self._setCaption(log, self.isError);
  4335. self.$container.removeClass('file-input-new file-input-ajax-new');
  4336. self._raise('fileselect', [numFiles, label]);
  4337. if (self.previewCache.count(true)) {
  4338. self._initPreviewActions();
  4339. }
  4340. },
  4341. _setThumbStatus: function ($thumb, status) {
  4342. var self = this;
  4343. if (!self.showPreview) {
  4344. return;
  4345. }
  4346. var icon = 'indicator' + status, msg = icon + 'Title',
  4347. css = 'file-preview-' + status.toLowerCase(),
  4348. $indicator = $thumb.find('.file-upload-indicator'),
  4349. config = self.fileActionSettings;
  4350. $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');
  4351. if (status === 'Success') {
  4352. $thumb.find('.file-drag-handle').remove();
  4353. }
  4354. $h.setHtml($indicator, config[icon]);
  4355. $indicator.attr('title', config[msg]);
  4356. $thumb.addClass(css);
  4357. if (status === 'Error' && !self.retryErrorUploads) {
  4358. $thumb.find('.kv-file-upload').attr('disabled', true);
  4359. }
  4360. },
  4361. _setProgressCancelled: function () {
  4362. var self = this;
  4363. self._setProgress(101, self.$progress, self.msgCancelled);
  4364. },
  4365. _setProgress: function (p, $el, error, stats) {
  4366. var self = this;
  4367. $el = $el || self.$progress;
  4368. if (!$el.length) {
  4369. return;
  4370. }
  4371. var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  4372. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  4373. template = pct < 100 ? self.progressTemplate :
  4374. (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t);
  4375. if (p >= 100) {
  4376. stats = '';
  4377. }
  4378. if (!$h.isEmpty(template)) {
  4379. if (pctLimit && pct > pctLimit && p <= 100) {
  4380. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  4381. } else {
  4382. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  4383. }
  4384. stats = stats || '';
  4385. out = out.setTokens({stats: stats});
  4386. $h.setHtml($el, out);
  4387. if (error) {
  4388. $h.setHtml($el.find('[role="progressbar"]'), error);
  4389. }
  4390. }
  4391. },
  4392. _hasFiles: function () {
  4393. var el = this.$element[0];
  4394. return !!(el && el.files && el.files.length);
  4395. },
  4396. _setFileDropZoneTitle: function () {
  4397. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  4398. if (self.isClickable) {
  4399. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  4400. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  4401. }
  4402. $zone.find('.' + self.dropZoneTitleClass).remove();
  4403. if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled ||
  4404. self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) {
  4405. return;
  4406. }
  4407. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  4408. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  4409. }
  4410. self.$container.removeClass('file-input-new');
  4411. $h.addCss(self.$container, 'file-input-ajax-new');
  4412. },
  4413. _getStats: function (stats) {
  4414. var self = this, pendingTime, t;
  4415. if (!self.showUploadStats || !stats || !stats.bitrate) {
  4416. return '';
  4417. }
  4418. t = self._getLayoutTemplate('stats');
  4419. pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime :
  4420. self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))});
  4421. return t.setTokens({
  4422. uploadSpeed: stats.bitrate,
  4423. pendingTime: pendingTime
  4424. });
  4425. },
  4426. _setResumableProgress: function (pct, stats, $thumb) {
  4427. var self = this, rm = self.resumableManager, obj = $thumb ? rm : self,
  4428. $prog = $thumb ? $thumb.find('.file-thumb-progress') : null;
  4429. if (obj.lastProgress === 0) {
  4430. obj.lastProgress = pct;
  4431. }
  4432. if (pct < obj.lastProgress) {
  4433. pct = obj.lastProgress;
  4434. }
  4435. self._setProgress(pct, $prog, null, self._getStats(stats));
  4436. obj.lastProgress = pct;
  4437. },
  4438. _toggleResumableProgress: function (template, message) {
  4439. var self = this, $progress = self.$progress;
  4440. if ($progress && $progress.length) {
  4441. $h.setHtml($progress, template.setTokens({
  4442. percent: 101,
  4443. status: message,
  4444. stats: ''
  4445. }));
  4446. }
  4447. },
  4448. _setFileUploadStats: function (id, pct, stats) {
  4449. var self = this, $prog = self.$progress;
  4450. if (!self.showPreview && (!$prog || !$prog.length)) {
  4451. return;
  4452. }
  4453. var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot,
  4454. totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats);
  4455. if (self.enableResumableUpload) {
  4456. var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded;
  4457. loaded += currUplSize;
  4458. totLoaded = fm.uploadedSize + loaded;
  4459. pct = $h.round(100 * loaded / currTotSize);
  4460. stats.pendingBytes = currTotSize - currUplSize;
  4461. self._setResumableProgress(pct, stats, $thumb);
  4462. pctTot = Math.floor(100 * totLoaded / totSize);
  4463. totStats.pendingBytes = totSize - totLoaded;
  4464. self._setResumableProgress(pctTot, totStats);
  4465. } else {
  4466. fm.setProgress(id, pct);
  4467. $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null;
  4468. self._setProgress(pct, $prog, null, self._getStats(stats));
  4469. $.each(fm.stats, function (id, cfg) {
  4470. totUpSize += cfg.loaded;
  4471. });
  4472. totStats.pendingBytes = totSize - totUpSize;
  4473. pctTot = $h.round(totUpSize / totSize * 100);
  4474. self._setProgress(pctTot, null, null, self._getStats(totStats));
  4475. }
  4476. },
  4477. _validateMinCount: function () {
  4478. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  4479. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  4480. self._noFilesError({});
  4481. return false;
  4482. }
  4483. return true;
  4484. },
  4485. _getFileCount: function (fileCount, includeInitial) {
  4486. var self = this, addCount = 0;
  4487. if (includeInitial === undefined) {
  4488. includeInitial = self.validateInitialCount && !self.overwriteInitial;
  4489. }
  4490. if (includeInitial) {
  4491. addCount = self.previewCache.count(true);
  4492. fileCount += addCount;
  4493. }
  4494. return fileCount;
  4495. },
  4496. _getFileId: function (file) {
  4497. return $h.getFileId(file, this.generateFileId);
  4498. },
  4499. _getFileName: function (file, defaultValue) {
  4500. var self = this, fileName = $h.getFileName(file);
  4501. return fileName ? self.slug(fileName) : defaultValue;
  4502. },
  4503. _getFileNames: function (skipNull) {
  4504. var self = this;
  4505. return self.filenames.filter(function (n) {
  4506. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  4507. });
  4508. },
  4509. _setPreviewError: function ($thumb, keepFile) {
  4510. var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads;
  4511. if (!keepFile || removeFrame) {
  4512. self.fileManager.remove($thumb);
  4513. }
  4514. if (!self.showPreview) {
  4515. return;
  4516. }
  4517. if (removeFrame) {
  4518. $thumb.remove();
  4519. return;
  4520. } else {
  4521. self._setThumbStatus($thumb, 'Error');
  4522. }
  4523. self._refreshUploadButton($thumb);
  4524. },
  4525. _refreshUploadButton: function ($thumb) {
  4526. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  4527. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  4528. if (!$btn.length) {
  4529. return;
  4530. }
  4531. if (self.retryErrorUploads) {
  4532. icon = cfg.uploadRetryIcon;
  4533. title = cfg.uploadRetryTitle;
  4534. }
  4535. $btn.attr('title', title);
  4536. $h.setHtml($btn, icon);
  4537. },
  4538. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  4539. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  4540. $imgEl, isValid;
  4541. if ($h.isEmpty(limit) || !$img.length) {
  4542. return;
  4543. }
  4544. $imgEl = $img[0];
  4545. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  4546. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  4547. if (isValid) {
  4548. return;
  4549. }
  4550. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  4551. self._showFileError(msg, params);
  4552. self._setPreviewError($thumb);
  4553. },
  4554. _getExifObj: function (data) {
  4555. var self = this, exifObj, error = $h.logMessages.exifWarning;
  4556. if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') {
  4557. exifObj = null;
  4558. return;
  4559. }
  4560. try {
  4561. exifObj = window.piexif ? window.piexif.load(data) : null;
  4562. } catch (err) {
  4563. exifObj = null;
  4564. error = err && err.message || '';
  4565. }
  4566. if (!exifObj) {
  4567. self._log($h.logMessages.badExifParser, {details: error});
  4568. }
  4569. return exifObj;
  4570. },
  4571. setImageOrientation: function ($img, $zoomImg, value, $thumb) {
  4572. var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark,
  4573. isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev;
  4574. if (invalidImg && invalidZoomImg) {
  4575. return;
  4576. }
  4577. ev = 'load.fileinputimageorient';
  4578. if (zoomOnly) {
  4579. $img = $zoomImg;
  4580. $zoomImg = null;
  4581. $img.css(self.previewSettings.image);
  4582. $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));
  4583. $mark = $(document.createElement('span')).insertBefore($img);
  4584. $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div);
  4585. } else {
  4586. isHidden = !$img.is(':visible');
  4587. }
  4588. $img.off(ev).on(ev, function () {
  4589. if (isHidden) {
  4590. self.$preview.removeClass('hide-content');
  4591. $thumb.find('.kv-file-content').css('visibility', 'hidden');
  4592. }
  4593. var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null,
  4594. h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value);
  4595. if (isHidden) {
  4596. $thumb.find('.kv-file-content').css('visibility', 'visible');
  4597. self.$preview.addClass('hide-content');
  4598. }
  4599. $img.data('orientation', value);
  4600. if (zoomImg) {
  4601. $zoomImg.data('orientation', value);
  4602. }
  4603. if (value < 5) {
  4604. $h.setTransform(img, r);
  4605. $h.setTransform(zoomImg, r);
  4606. return;
  4607. }
  4608. var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)),
  4609. scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor,
  4610. s = ' scale(' + Math.abs(scale) + ')';
  4611. $h.setTransform(img, r + s);
  4612. $h.setTransform(zoomImg, r + s);
  4613. if (zoomOnly) {
  4614. $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail');
  4615. $mark.remove();
  4616. $div.remove();
  4617. }
  4618. });
  4619. },
  4620. _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) {
  4621. var self = this, exifObj = null, value, autoOrientImage = self.autoOrientImage, selector;
  4622. if (self.canOrientImage) {
  4623. $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none'));
  4624. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4625. return;
  4626. }
  4627. selector = $h.getZoomSelector(previewId, ' img');
  4628. exifObj = autoOrientImage ? self._getExifObj(iData) : null;
  4629. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  4630. if (!value) {
  4631. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4632. return;
  4633. }
  4634. self.setImageOrientation($img, $(selector), value, self._getFrame(previewId));
  4635. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  4636. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4637. },
  4638. _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) {
  4639. var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId),
  4640. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  4641. fname = fname || 'Untitled';
  4642. $img.one('load', function () {
  4643. w1 = $thumb.width();
  4644. w2 = $preview.width();
  4645. if (w1 > w2) {
  4646. $img.css('width', '100%');
  4647. }
  4648. params = {ind: i, id: previewId, fileId: fileId};
  4649. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  4650. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  4651. if (!self.resizeImage) {
  4652. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  4653. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  4654. }
  4655. self._raise('fileimageloaded', [previewId]);
  4656. self.fileManager.addImage(fileId, {
  4657. ind: i,
  4658. img: $img,
  4659. thumb: $thumb,
  4660. pid: previewId,
  4661. typ: ftype,
  4662. siz: fsize,
  4663. validated: false,
  4664. imgData: iData,
  4665. exifObj: exifObj
  4666. });
  4667. $thumb.data('exif', exifObj);
  4668. self._validateAllImages();
  4669. }).one('error', function () {
  4670. self._raise('fileimageloaderror', [previewId]);
  4671. });
  4672. },
  4673. _validateAllImages: function () {
  4674. var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize,
  4675. minSize = self.resizeIfSizeMoreThan;
  4676. if (numImgs !== self.fileManager.totalImages) {
  4677. return;
  4678. }
  4679. self._raise('fileimagesloaded');
  4680. if (!self.resizeImage) {
  4681. return;
  4682. }
  4683. $.each(self.fileManager.loadedImages, function (id, config) {
  4684. if (!config.validated) {
  4685. fsize = config.siz;
  4686. if (fsize && fsize > minSize * self.bytesToKB) {
  4687. self._getResizedImage(id, config, counter, numImgs);
  4688. }
  4689. config.validated = true;
  4690. }
  4691. });
  4692. },
  4693. _getResizedImage: function (id, config, counter, numImgs) {
  4694. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  4695. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  4696. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  4697. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  4698. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams;
  4699. throwError = function (msg, params, ev) {
  4700. if (self.isAjaxUpload) {
  4701. self._showFileError(msg, params, ev);
  4702. } else {
  4703. self._showError(msg, params, ev);
  4704. }
  4705. self._setPreviewError($thumb);
  4706. };
  4707. file = self.fileManager.getFile(id);
  4708. params = {id: pid, 'index': ind, fileId: id};
  4709. evParams = [id, pid, ind];
  4710. if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  4711. if (isValidImage && file) {
  4712. self._raise('fileimageresized', evParams);
  4713. }
  4714. counter.val++;
  4715. if (counter.val === numImgs) {
  4716. self._raise('fileimagesresized');
  4717. }
  4718. if (!isValidImage) {
  4719. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4720. return;
  4721. }
  4722. }
  4723. type = type || self.resizeDefaultImageType;
  4724. chkWidth = width > maxWidth;
  4725. chkHeight = height > maxHeight;
  4726. if (self.resizePreference === 'width') {
  4727. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  4728. } else {
  4729. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  4730. }
  4731. self._resetCanvas();
  4732. width *= ratio;
  4733. height *= ratio;
  4734. canvas.width = width;
  4735. canvas.height = height;
  4736. try {
  4737. context.drawImage(img, 0, 0, width, height);
  4738. dataURI = canvas.toDataURL(type, self.resizeQuality);
  4739. if (exifObj) {
  4740. exifStr = window.piexif.dump(exifObj);
  4741. dataURI = window.piexif.insert(exifStr, dataURI);
  4742. }
  4743. blob = $h.dataURI2Blob(dataURI);
  4744. self.fileManager.setFile(id, blob);
  4745. self._raise('fileimageresized', evParams);
  4746. counter.val++;
  4747. if (counter.val === numImgs) {
  4748. self._raise('fileimagesresized', [undefined, undefined]);
  4749. }
  4750. if (!(blob instanceof Blob)) {
  4751. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4752. }
  4753. } catch (err) {
  4754. counter.val++;
  4755. if (counter.val === numImgs) {
  4756. self._raise('fileimagesresized', [undefined, undefined]);
  4757. }
  4758. msg = self.msgImageResizeException.replace('{errors}', err.message);
  4759. throwError(msg, params, 'fileimageresizeexception');
  4760. }
  4761. },
  4762. _showProgress: function () {
  4763. var self = this;
  4764. if (self.$progress && self.$progress.length) {
  4765. self.$progress.show();
  4766. }
  4767. },
  4768. _hideProgress: function () {
  4769. var self = this;
  4770. if (self.$progress && self.$progress.length) {
  4771. self.$progress.hide();
  4772. }
  4773. },
  4774. _initBrowse: function ($container) {
  4775. var self = this, $el = self.$element;
  4776. if (self.showBrowse) {
  4777. self.$btnFile = $container.find('.btn-file').append($el);
  4778. } else {
  4779. $el.appendTo($container).attr('tabindex', -1);
  4780. $h.addCss($el, 'file-no-browse');
  4781. }
  4782. },
  4783. _initClickable: function () {
  4784. var self = this, $zone, $tmpZone;
  4785. if (!self.isClickable) {
  4786. return;
  4787. }
  4788. $zone = self.$dropZone;
  4789. if (!self.isAjaxUpload) {
  4790. $tmpZone = self.$preview.find('.file-default-preview');
  4791. if ($tmpZone.length) {
  4792. $zone = $tmpZone;
  4793. }
  4794. }
  4795. $h.addCss($zone, 'clickable');
  4796. $zone.attr('tabindex', -1);
  4797. self._handler($zone, 'click', function (e) {
  4798. var $tar = $(e.target);
  4799. if (!self.$errorContainer.is(':visible') && (!$tar.parents(
  4800. '.file-preview-thumbnails').length || $tar.parents(
  4801. '.file-default-preview').length)) {
  4802. self.$element.data('zoneClicked', true).trigger('click');
  4803. $zone.blur();
  4804. }
  4805. });
  4806. },
  4807. _initCaption: function () {
  4808. var self = this, cap = self.initialCaption || '';
  4809. if (self.overwriteInitial || $h.isEmpty(cap)) {
  4810. self.$caption.val('');
  4811. return false;
  4812. }
  4813. self._setCaption(cap);
  4814. return true;
  4815. },
  4816. _setCaption: function (content, isError) {
  4817. var self = this, title, out, icon, n, cap, file;
  4818. if (!self.$caption.length) {
  4819. return;
  4820. }
  4821. self.$captionContainer.removeClass('icon-visible');
  4822. if (isError) {
  4823. title = $('<div>' + self.msgValidationError + '</div>').text();
  4824. n = self.fileManager.count();
  4825. if (n) {
  4826. file = self.fileManager.getFirstFile();
  4827. cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n);
  4828. } else {
  4829. cap = self._getMsgSelected(self.msgNo);
  4830. }
  4831. out = $h.isEmpty(content) ? cap : content;
  4832. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  4833. } else {
  4834. if ($h.isEmpty(content)) {
  4835. self.$caption.attr('title', '');
  4836. return;
  4837. }
  4838. title = $('<div>' + content + '</div>').text();
  4839. out = title;
  4840. icon = self._getLayoutTemplate('fileIcon');
  4841. }
  4842. self.$captionContainer.addClass('icon-visible');
  4843. self.$caption.attr('title', title).val(out);
  4844. $h.setHtml(self.$captionIcon, icon);
  4845. },
  4846. _createContainer: function () {
  4847. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  4848. $container = $h.createElement($h.cspBuffer.stash(self._renderMain()));
  4849. $h.cspBuffer.apply($container);
  4850. $container.insertBefore(self.$element).attr(attribs);
  4851. self._initBrowse($container);
  4852. if (self.theme) {
  4853. $container.addClass('theme-' + self.theme);
  4854. }
  4855. return $container;
  4856. },
  4857. _refreshContainer: function () {
  4858. var self = this, $container = self.$container, $el = self.$element;
  4859. $el.insertAfter($container);
  4860. $h.setHtml($container, self._renderMain());
  4861. self._initBrowse($container);
  4862. self._validateDisabled();
  4863. },
  4864. _validateDisabled: function () {
  4865. var self = this;
  4866. self.$caption.attr({readonly: self.isDisabled});
  4867. },
  4868. _setTabIndex: function (type, html) {
  4869. var self = this, index = self.tabIndexConfig[type];
  4870. return html.setTokens({
  4871. tabIndexConfig: index === undefined || index === null ? '' : 'tabindex="' + index + '"'
  4872. });
  4873. },
  4874. _renderMain: function () {
  4875. var self = this,
  4876. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  4877. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  4878. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  4879. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  4880. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  4881. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  4882. caption = self._setTabIndex('caption', caption);
  4883. return self.mainTemplate.setTokens({
  4884. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  4885. 'inputGroupClass': self.inputGroupClass,
  4886. 'preview': preview,
  4887. 'close': close,
  4888. 'caption': caption,
  4889. 'upload': self._renderButton('upload'),
  4890. 'remove': self._renderButton('remove'),
  4891. 'cancel': self._renderButton('cancel'),
  4892. 'pause': self._renderButton('pause'),
  4893. 'browse': self._renderButton('browse')
  4894. });
  4895. },
  4896. _renderButton: function (type) {
  4897. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  4898. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  4899. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  4900. switch (type) {
  4901. case 'remove':
  4902. if (!self.showRemove) {
  4903. return '';
  4904. }
  4905. break;
  4906. case 'cancel':
  4907. if (!self.showCancel) {
  4908. return '';
  4909. }
  4910. css += ' kv-hidden';
  4911. break;
  4912. case 'pause':
  4913. if (!self.showPause) {
  4914. return '';
  4915. }
  4916. css += ' kv-hidden';
  4917. break;
  4918. case 'upload':
  4919. if (!self.showUpload) {
  4920. return '';
  4921. }
  4922. if (self.isAjaxUpload && !self.isDisabled) {
  4923. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  4924. } else {
  4925. btnType = 'submit';
  4926. }
  4927. break;
  4928. case 'browse':
  4929. if (!self.showBrowse) {
  4930. return '';
  4931. }
  4932. tmplt = self._getLayoutTemplate('btnBrowse');
  4933. break;
  4934. default:
  4935. return '';
  4936. }
  4937. tmplt = self._setTabIndex(type, tmplt);
  4938. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  4939. if (!$h.isEmpty(label)) {
  4940. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  4941. }
  4942. return tmplt.setTokens({
  4943. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  4944. });
  4945. },
  4946. _renderThumbProgress: function () {
  4947. var self = this;
  4948. return '<div class="file-thumb-progress kv-hidden">' +
  4949. self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) +
  4950. '</div>';
  4951. },
  4952. _renderFileFooter: function (cat, caption, size, width, isError) {
  4953. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  4954. upl = config.showUpload, zoom = config.showZoom, out, params,
  4955. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  4956. ind = isError ? config.indicatorError : config.indicatorNew,
  4957. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  4958. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  4959. size = self._getSize(size);
  4960. params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator};
  4961. if (self.isAjaxUpload) {
  4962. params.progress = self._renderThumbProgress();
  4963. params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false);
  4964. } else {
  4965. params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false);
  4966. }
  4967. out = template.setTokens(params);
  4968. out = $h.replaceTags(out, self.previewThumbTags);
  4969. return out;
  4970. },
  4971. _renderFileActions: function (
  4972. cfg,
  4973. showUpl,
  4974. showDwn,
  4975. showDel,
  4976. showZoom,
  4977. showDrag,
  4978. disabled,
  4979. url,
  4980. key,
  4981. isInit,
  4982. dUrl,
  4983. dFile
  4984. ) {
  4985. var self = this;
  4986. if (!cfg.type && isInit) {
  4987. cfg.type = 'image';
  4988. }
  4989. if (self.enableResumableUpload) {
  4990. showUpl = false;
  4991. } else {
  4992. if (typeof showUpl === 'function') {
  4993. showUpl = showUpl(cfg);
  4994. }
  4995. }
  4996. if (typeof showDwn === 'function') {
  4997. showDwn = showDwn(cfg);
  4998. }
  4999. if (typeof showDel === 'function') {
  5000. showDel = showDel(cfg);
  5001. }
  5002. if (typeof showZoom === 'function') {
  5003. showZoom = showZoom(cfg);
  5004. }
  5005. if (typeof showDrag === 'function') {
  5006. showDrag = showDrag(cfg);
  5007. }
  5008. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  5009. return '';
  5010. }
  5011. var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css,
  5012. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  5013. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  5014. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  5015. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  5016. if (showDel) {
  5017. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  5018. 'removeClass': removeClass,
  5019. 'removeIcon': config.removeIcon,
  5020. 'removeTitle': config.removeTitle,
  5021. 'dataUrl': vUrl,
  5022. 'dataKey': vKey,
  5023. 'key': key
  5024. });
  5025. }
  5026. if (showUpl) {
  5027. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  5028. 'uploadClass': config.uploadClass,
  5029. 'uploadIcon': config.uploadIcon,
  5030. 'uploadTitle': config.uploadTitle
  5031. });
  5032. }
  5033. if (showDwn) {
  5034. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  5035. 'downloadClass': config.downloadClass,
  5036. 'downloadIcon': config.downloadIcon,
  5037. 'downloadTitle': config.downloadTitle,
  5038. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  5039. });
  5040. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  5041. }
  5042. if (showZoom) {
  5043. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  5044. 'zoomClass': config.zoomClass,
  5045. 'zoomIcon': config.zoomIcon,
  5046. 'zoomTitle': config.zoomTitle
  5047. });
  5048. }
  5049. if (showDrag && isInit) {
  5050. css = 'drag-handle-init ' + config.dragClass;
  5051. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  5052. 'dragClass': css,
  5053. 'dragTitle': config.dragTitle,
  5054. 'dragIcon': config.dragIcon
  5055. });
  5056. }
  5057. return template.setTokens({
  5058. 'delete': btnDelete,
  5059. 'upload': btnUpload,
  5060. 'download': btnDownload,
  5061. 'zoom': btnZoom,
  5062. 'drag': btnDrag,
  5063. 'other': otherButtons
  5064. });
  5065. },
  5066. _browse: function (e) {
  5067. var self = this;
  5068. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  5069. return;
  5070. }
  5071. if (self.isError && !self.isAjaxUpload) {
  5072. self.clear();
  5073. }
  5074. if (self.focusCaptionOnBrowse) {
  5075. self.$captionContainer.focus();
  5076. }
  5077. },
  5078. _change: function (e) {
  5079. var self = this;
  5080. $(document.body).off('focusin.fileinput focusout.fileinput');
  5081. if (self.changeTriggered) {
  5082. return;
  5083. }
  5084. self._setLoading('show');
  5085. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  5086. tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(),
  5087. total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')),
  5088. maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount,
  5089. inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0),
  5090. throwError = function (mesg, file, previewId, index) {
  5091. var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}),
  5092. p2 = {id: previewId, index: index, file: file, files: files};
  5093. self.isPersistentError = true;
  5094. self._setLoading('hide');
  5095. return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2);
  5096. },
  5097. maxCountCheck = function (n, m, all) {
  5098. var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany;
  5099. msg = msg.replace('{m}', m).replace('{n}', n);
  5100. self.isError = throwError(msg, null, null, null);
  5101. self.$captionContainer.removeClass('icon-visible');
  5102. self._setCaption('', true);
  5103. self.$container.removeClass('file-input-new file-input-ajax-new');
  5104. };
  5105. self.reader = null;
  5106. self._resetUpload();
  5107. self._hideFileIcon();
  5108. if (self.dropZoneEnabled) {
  5109. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5110. }
  5111. if (!isAjaxUpload) {
  5112. if (e.target && e.target.files === undefined) {
  5113. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  5114. } else {
  5115. files = e.target.files || {};
  5116. }
  5117. }
  5118. tfiles = files;
  5119. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  5120. if (!isAjaxUpload) {
  5121. self.clear();
  5122. }
  5123. self._raise('fileselectnone');
  5124. return;
  5125. }
  5126. self._resetErrors();
  5127. len = tfiles.length;
  5128. initCount = isAjaxUpload ? (self.fileManager.count() + len) : len;
  5129. total = self._getFileCount(initCount, inclAll ? false : undefined);
  5130. if (maxCount > 0 && total > maxCount) {
  5131. if (!self.autoReplace || len > maxCount) {
  5132. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  5133. return;
  5134. }
  5135. if (total > maxCount) {
  5136. self._resetPreviewThumbs(isAjaxUpload);
  5137. }
  5138. } else {
  5139. if (inclAll) {
  5140. total = self._getFileCount(initCount, true);
  5141. if (maxTotCount > 0 && total > maxTotCount) {
  5142. if (!self.autoReplace || len > maxCount) {
  5143. maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true);
  5144. return;
  5145. }
  5146. if (total > maxCount) {
  5147. self._resetPreviewThumbs(isAjaxUpload);
  5148. }
  5149. }
  5150. }
  5151. if (!isAjaxUpload || flagSingle) {
  5152. self._resetPreviewThumbs(false);
  5153. if (flagSingle) {
  5154. self.clearFileStack();
  5155. }
  5156. } else {
  5157. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) {
  5158. self._resetPreviewThumbs(true);
  5159. }
  5160. }
  5161. }
  5162. self.readFiles(tfiles);
  5163. self._setLoading('hide');
  5164. },
  5165. _abort: function (params) {
  5166. var self = this, data;
  5167. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  5168. data = $.extend(true, {}, self._getOutData(null), params);
  5169. data.abortData = self.ajaxAborted.data || {};
  5170. data.abortMessage = self.ajaxAborted.message;
  5171. self._setProgress(101, self.$progress, self.msgCancelled);
  5172. self._showFileError(self.ajaxAborted.message, data, 'filecustomerror');
  5173. self.cancel();
  5174. self.unlock();
  5175. return true;
  5176. }
  5177. return !!self.ajaxAborted;
  5178. },
  5179. _resetFileStack: function () {
  5180. var self = this, i = 0;
  5181. self._getThumbs().each(function () {
  5182. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id');
  5183. if (ind === '-1' || ind === -1) {
  5184. return;
  5185. }
  5186. if (!self._getThumbFile($thumb)) {
  5187. $thumb.attr({'data-fileindex': i});
  5188. i++;
  5189. } else {
  5190. $thumb.attr({'data-fileindex': '-1'});
  5191. }
  5192. self._getZoom(pid).attr({
  5193. 'data-fileindex': $thumb.attr('data-fileindex')
  5194. });
  5195. });
  5196. },
  5197. _isFileSelectionValid: function (cnt) {
  5198. var self = this;
  5199. cnt = cnt || 0;
  5200. if (self.required && !self.getFilesCount()) {
  5201. self.$errorContainer.html('');
  5202. self._showFileError(self.msgFileRequired);
  5203. return false;
  5204. }
  5205. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  5206. self._noFilesError({});
  5207. return false;
  5208. }
  5209. return true;
  5210. },
  5211. _canPreview: function (file) {
  5212. var self = this;
  5213. if (!file || !self.showPreview || !self.$preview || !self.$preview.length) {
  5214. return false;
  5215. }
  5216. var name = file.name || '', type = file.type || '', size = (file.size || 0) / self.bytesToKB,
  5217. cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview,
  5218. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  5219. exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes,
  5220. dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [],
  5221. maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0,
  5222. expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'),
  5223. expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i');
  5224. allowedTypes = !types || types.indexOf(cat) !== -1;
  5225. allowedMimes = !mimes || mimes.indexOf(type) !== -1;
  5226. allowedExts = !exts.length || $h.compare(name, expAllExt);
  5227. skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) ||
  5228. (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize);
  5229. return !skipPreview && (allowedTypes || allowedMimes || allowedExts);
  5230. },
  5231. addToStack: function (file, id) {
  5232. this.fileManager.add(file, id);
  5233. },
  5234. clearFileStack: function () {
  5235. var self = this;
  5236. self.fileManager.clear();
  5237. self._initResumableUpload();
  5238. if (self.enableResumableUpload) {
  5239. if (self.showPause === null) {
  5240. self.showPause = true;
  5241. }
  5242. if (self.showCancel === null) {
  5243. self.showCancel = false;
  5244. }
  5245. } else {
  5246. self.showPause = false;
  5247. if (self.showCancel === null) {
  5248. self.showCancel = true;
  5249. }
  5250. }
  5251. return self.$element;
  5252. },
  5253. getFileStack: function () {
  5254. return this.fileManager.stack;
  5255. },
  5256. getFileList: function () {
  5257. return this.fileManager.list();
  5258. },
  5259. getFilesSize: function () {
  5260. return this.fileManager.getTotalSize();
  5261. },
  5262. getFilesCount: function (includeInitial) {
  5263. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  5264. if (includeInitial) {
  5265. len += self.previewCache.count(true);
  5266. }
  5267. return self._getFileCount(len);
  5268. },
  5269. _initCapStatus: function (status) {
  5270. var self = this, $cap = self.$caption;
  5271. $cap.removeClass('is-valid file-processing');
  5272. if (!status) {
  5273. return;
  5274. }
  5275. if (status === 'processing') {
  5276. $cap.addClass('file-processing');
  5277. } else {
  5278. $cap.addClass('is-valid');
  5279. }
  5280. },
  5281. _setLoading: function (type) {
  5282. var self = this;
  5283. self.$previewStatus.html(type === 'hide' ? '' : self.msgProcessing);
  5284. self.$container.removeClass('file-thumb-loading');
  5285. self._initCapStatus(type === 'hide' ? '' : 'processing');
  5286. if (type !== 'hide') {
  5287. if (self.dropZoneEnabled) {
  5288. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5289. }
  5290. self.$container.addClass('file-thumb-loading');
  5291. }
  5292. },
  5293. _initFileSelected: function () {
  5294. var self = this, $el = self.$element, $body = $(document.body), ev = 'focusin.fileinput focusout.fileinput';
  5295. if ($body.length) {
  5296. $body.off(ev).on('focusout.fileinput', function () {
  5297. self._setLoading('show');
  5298. }).on('focusin.fileinput', function () {
  5299. setTimeout(function () {
  5300. if (!$el.val()) {
  5301. self._setLoading('hide');
  5302. self._setFileDropZoneTitle();
  5303. }
  5304. $body.off(ev);
  5305. }, 2500);
  5306. });
  5307. } else {
  5308. self._setLoading('hide');
  5309. }
  5310. },
  5311. readFiles: function (files) {
  5312. this.reader = new FileReader();
  5313. var self = this, reader = self.reader, $container = self.$previewContainer,
  5314. $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress,
  5315. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  5316. readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  5317. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  5318. throwError = function (msg, file, previewId, index, fileId) {
  5319. var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files),
  5320. {id: previewId, index: index, fileId: fileId}),
  5321. p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files};
  5322. self._previewDefault(file, true);
  5323. $thumb = self._getFrame(previewId, true);
  5324. self._setLoading('hide');
  5325. if (self.isAjaxUpload) {
  5326. setTimeout(function () {
  5327. readFile(index + 1);
  5328. }, self.processDelay);
  5329. } else {
  5330. self.unlock();
  5331. numFiles = 0;
  5332. }
  5333. if (self.removeFromPreviewOnError && $thumb.length) {
  5334. $thumb.remove();
  5335. } else {
  5336. self._initFileActions();
  5337. $thumb.find('.kv-file-upload').remove();
  5338. }
  5339. self.isPersistentError = true;
  5340. self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2);
  5341. self._updateFileDetails(numFiles);
  5342. };
  5343. self.fileManager.clearImages();
  5344. $.each(files, function (key, file) {
  5345. var func = self.fileTypeSettings.image;
  5346. if (func && func(file.type)) {
  5347. self.fileManager.totalImages++;
  5348. }
  5349. });
  5350. readFile = function (i) {
  5351. var $error = self.$errorContainer, errors, fm = self.fileManager;
  5352. if (i >= numFiles) {
  5353. self.unlock();
  5354. if (self.duplicateErrors.length) {
  5355. errors = '<li>' + self.duplicateErrors.join('</li><li>') + '</li>';
  5356. if ($error.find('ul').length === 0) {
  5357. $h.setHtml($error, self.errorCloseButton + '<ul>' + errors + '</ul>');
  5358. } else {
  5359. $error.find('ul').append(errors);
  5360. }
  5361. $error.fadeIn(self.fadeDelay);
  5362. self._handler($error.find('.kv-error-close'), 'click', function () {
  5363. $error.fadeOut(self.fadeDelay);
  5364. });
  5365. self.duplicateErrors = [];
  5366. }
  5367. if (self.isAjaxUpload) {
  5368. self._raise('filebatchselected', [fm.stack]);
  5369. if (fm.count() === 0 && !self.isError) {
  5370. self.reset();
  5371. }
  5372. } else {
  5373. self._raise('filebatchselected', [files]);
  5374. }
  5375. $container.removeClass('file-thumb-loading');
  5376. self._initCapStatus('valid');
  5377. $status.html('');
  5378. return;
  5379. }
  5380. self.lock(true);
  5381. var file = files[i], id = self._getFileId(file), previewId = previewInitId + '-' + id, fSizeKB, j, msg,
  5382. fnImage = settings.image, typ, chk, typ1, typ2,
  5383. caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / self.bytesToKB,
  5384. fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
  5385. strTypes = '', fileId, canLoad, fileReaderAborted = false,
  5386. func, knownTypes = 0, isImage, txtFlag, processFileLoaded = function () {
  5387. var isImageResized = !!fm.loadedImages[id], msg = msgProgress.setTokens({
  5388. 'index': i + 1,
  5389. 'files': numFiles,
  5390. 'percent': 50,
  5391. 'name': caption
  5392. });
  5393. setTimeout(function () {
  5394. $status.html(msg);
  5395. self._updateFileDetails(numFiles);
  5396. readFile(i + 1);
  5397. }, self.processDelay);
  5398. if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) {
  5399. if (!isImageResized) {
  5400. fm.add(file);
  5401. }
  5402. } else {
  5403. if (isImageResized) {
  5404. fm.removeFile(id);
  5405. }
  5406. }
  5407. };
  5408. if (!file) {
  5409. return;
  5410. }
  5411. fileId = fm.getId(file);
  5412. if (typLen > 0) {
  5413. for (j = 0; j < typLen; j++) {
  5414. typ1 = fileTypes[j];
  5415. typ2 = self.msgFileTypes[typ1] || typ1;
  5416. strTypes += j === 0 ? typ2 : ', ' + typ2;
  5417. }
  5418. }
  5419. if (caption === false) {
  5420. readFile(i + 1);
  5421. return;
  5422. }
  5423. if (caption.length === 0) {
  5424. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
  5425. throwError(msg, file, previewId, i, fileId);
  5426. return;
  5427. }
  5428. if (!$h.isEmpty(fileExt)) {
  5429. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  5430. }
  5431. fSizeKB = fileSize.toFixed(2);
  5432. if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) {
  5433. var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files};
  5434. msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB});
  5435. if (self.isAjaxUpload) {
  5436. self.duplicateErrors.push(msg);
  5437. self.isDuplicateError = true;
  5438. self._raise('fileduplicateerror', [file, fileId, caption, fSizeKB, previewId, i]);
  5439. readFile(i + 1);
  5440. self._updateFileDetails(numFiles);
  5441. } else {
  5442. self._showError(msg, p2);
  5443. self.unlock();
  5444. numFiles = 0;
  5445. self._clearFileInput();
  5446. self.reset();
  5447. self._updateFileDetails(numFiles);
  5448. }
  5449. return;
  5450. }
  5451. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  5452. msg = self.msgSizeTooLarge.setTokens({
  5453. 'name': caption,
  5454. 'size': fSizeKB,
  5455. 'maxSize': self.maxFileSize
  5456. });
  5457. throwError(msg, file, previewId, i, fileId);
  5458. return;
  5459. }
  5460. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  5461. msg = self.msgSizeTooSmall.setTokens({
  5462. 'name': caption,
  5463. 'size': fSizeKB,
  5464. 'minSize': self.minFileSize
  5465. });
  5466. throwError(msg, file, previewId, i, fileId);
  5467. return;
  5468. }
  5469. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  5470. for (j = 0; j < fileTypes.length; j += 1) {
  5471. typ = fileTypes[j];
  5472. func = settings[typ];
  5473. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
  5474. $h.getFileName(file)) ? 1 : 0);
  5475. }
  5476. if (fileCount === 0) {
  5477. msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes});
  5478. throwError(msg, file, previewId, i, fileId);
  5479. return;
  5480. }
  5481. }
  5482. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  5483. chk = $h.compare(caption, fileExtExpr);
  5484. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  5485. if (fileCount === 0) {
  5486. msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt});
  5487. throwError(msg, file, previewId, i, fileId);
  5488. return;
  5489. }
  5490. }
  5491. if (!self._canPreview(file)) {
  5492. canLoad = self.isAjaxUpload && self._raise('filebeforeload', [file, i, reader]);
  5493. if (self.isAjaxUpload && canLoad) {
  5494. fm.add(file);
  5495. }
  5496. if (self.showPreview && canLoad) {
  5497. $container.addClass('file-thumb-loading');
  5498. self._initCapStatus('processing');
  5499. self._previewDefault(file);
  5500. self._initFileActions();
  5501. }
  5502. setTimeout(function () {
  5503. if (canLoad) {
  5504. self._updateFileDetails(numFiles);
  5505. }
  5506. readFile(i + 1);
  5507. self._raise('fileloaded', [file, previewId, id, i]);
  5508. }, 10);
  5509. return;
  5510. }
  5511. isImage = fnImage(file.type, caption);
  5512. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  5513. $container.addClass('file-thumb-loading');
  5514. self._initCapStatus('processing');
  5515. reader.onerror = function (evt) {
  5516. self._errorHandler(evt, caption);
  5517. };
  5518. reader.onload = function (theFile) {
  5519. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readImage = function () {
  5520. var newReader = new FileReader();
  5521. newReader.onerror = function (theFileNew) {
  5522. self._errorHandler(theFileNew, caption);
  5523. };
  5524. newReader.onload = function (theFileNew) {
  5525. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5526. fileReaderAborted = true;
  5527. self._resetCaption();
  5528. reader.abort();
  5529. $status.html('');
  5530. $container.removeClass('file-thumb-loading');
  5531. self._initCapStatus('valid');
  5532. self.enable();
  5533. return;
  5534. }
  5535. self._previewFile(i, file, theFileNew, previewData, fileInfo);
  5536. self._initFileActions();
  5537. processFileLoaded();
  5538. };
  5539. newReader.readAsDataURL(file);
  5540. };
  5541. fileInfo = {'name': caption, 'type': file.type};
  5542. $.each(settings, function (k, f) {
  5543. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
  5544. knownTypes++;
  5545. }
  5546. });
  5547. if (knownTypes === 0) { // auto detect mime types from content if no known file types detected
  5548. uint = new Uint8Array(theFile.target.result);
  5549. for (j = 0; j < uint.length; j++) {
  5550. byte = uint[j].toString(16);
  5551. bytes.push(byte);
  5552. }
  5553. hex = bytes.join('').toLowerCase().substring(0, 8);
  5554. mime = $h.getMimeType(hex, '', '');
  5555. if ($h.isEmpty(mime)) { // look for ascii text content
  5556. contents = $h.arrayBuffer2String(reader.result);
  5557. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  5558. }
  5559. fileInfo = {'name': caption, 'type': mime};
  5560. isImage = fnImage(mime, '');
  5561. if (isImage) {
  5562. readImage(txtFlag);
  5563. return;
  5564. }
  5565. }
  5566. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5567. fileReaderAborted = true;
  5568. self._resetCaption();
  5569. reader.abort();
  5570. $status.html('');
  5571. $container.removeClass('file-thumb-loading');
  5572. self._initCapStatus('valid');
  5573. self.enable();
  5574. return;
  5575. }
  5576. self._previewFile(i, file, theFile, previewData, fileInfo);
  5577. self._initFileActions();
  5578. processFileLoaded();
  5579. };
  5580. reader.onprogress = function (data) {
  5581. if (data.lengthComputable) {
  5582. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  5583. msg = msgProgress.setTokens({
  5584. 'index': i + 1,
  5585. 'files': numFiles,
  5586. 'percent': progress,
  5587. 'name': caption
  5588. });
  5589. setTimeout(function () {
  5590. if (!fileReaderAborted) {
  5591. $status.html(msg);
  5592. }
  5593. }, self.processDelay);
  5594. }
  5595. };
  5596. if (isImage) {
  5597. reader.readAsDataURL(file);
  5598. } else {
  5599. reader.readAsArrayBuffer(file);
  5600. }
  5601. };
  5602. readFile(0);
  5603. self._updateFileDetails(numFiles);
  5604. },
  5605. lock: function (selectMode) {
  5606. var self = this, $container = self.$container;
  5607. self._resetErrors();
  5608. self.disable();
  5609. if (!selectMode && self.showCancel) {
  5610. $container.find('.fileinput-cancel').show();
  5611. }
  5612. if (!selectMode && self.showPause) {
  5613. $container.find('.fileinput-pause').show();
  5614. }
  5615. self._initCapStatus('processing');
  5616. self._raise('filelock', [self.fileManager.stack, self._getExtraData()]);
  5617. return self.$element;
  5618. },
  5619. unlock: function (reset) {
  5620. var self = this, $container = self.$container;
  5621. if (reset === undefined) {
  5622. reset = true;
  5623. }
  5624. self.enable();
  5625. $container.removeClass('is-locked');
  5626. if (self.showCancel) {
  5627. $container.find('.fileinput-cancel').hide();
  5628. }
  5629. if (self.showPause) {
  5630. $container.find('.fileinput-pause').hide();
  5631. }
  5632. if (reset) {
  5633. self._resetFileStack();
  5634. }
  5635. self._initCapStatus();
  5636. self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]);
  5637. return self.$element;
  5638. },
  5639. resume: function () {
  5640. var self = this, fm = self.fileManager, flag = false, rm = self.resumableManager;
  5641. fm.bpsLog = [];
  5642. fm.bps = 0;
  5643. if (!self.enableResumableUpload) {
  5644. return self.$element;
  5645. }
  5646. if (self.paused) {
  5647. self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume);
  5648. } else {
  5649. flag = true;
  5650. }
  5651. self.paused = false;
  5652. if (flag) {
  5653. self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin);
  5654. }
  5655. setTimeout(function () {
  5656. rm.upload();
  5657. }, self.processDelay);
  5658. return self.$element;
  5659. },
  5660. paste: function (e) {
  5661. var self = this, ev = e.originalEvent, files = ev.clipboardData && ev.clipboardData.files || null;
  5662. if (files) {
  5663. self._dropFiles(e, files);
  5664. }
  5665. return self.$element;
  5666. },
  5667. pause: function () {
  5668. var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i,
  5669. pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager,
  5670. pool = tm.getPool(rm.id);
  5671. if (!self.enableResumableUpload) {
  5672. return self.$element;
  5673. } else {
  5674. if (pool) {
  5675. pool.cancel();
  5676. }
  5677. }
  5678. self._raise('fileuploadpaused', [self.fileManager, rm]);
  5679. if (len > 0) {
  5680. for (i = 0; i < len; i += 1) {
  5681. self.paused = true;
  5682. xhr[i].abort();
  5683. }
  5684. }
  5685. if (self.showPreview) {
  5686. self._getThumbs().each(function () {
  5687. var $thumb = $(this), t = self._getLayoutTemplate('stats'), stats,
  5688. $indicator = $thumb.find('.file-upload-indicator');
  5689. $thumb.removeClass('file-uploading');
  5690. if ($indicator.attr('title') === actions.indicatorLoadingTitle) {
  5691. self._setThumbStatus($thumb, 'Paused');
  5692. stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''});
  5693. self.paused = true;
  5694. self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats);
  5695. }
  5696. if (!self._getThumbFile($thumb)) {
  5697. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5698. }
  5699. });
  5700. }
  5701. self._setProgress(101, self.$progress, self.msgPaused);
  5702. return self.$element;
  5703. },
  5704. cancel: function () {
  5705. var self = this, xhr = self.ajaxRequests,
  5706. rm = self.resumableManager, tm = self.taskManager,
  5707. pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i;
  5708. if (self.enableResumableUpload && pool) {
  5709. pool.cancel().done(function () {
  5710. self._setProgressCancelled();
  5711. });
  5712. rm.reset();
  5713. self._raise('fileuploadcancelled', [self.fileManager, rm]);
  5714. } else {
  5715. self._raise('fileuploadcancelled', [self.fileManager]);
  5716. }
  5717. self._initAjax();
  5718. if (len > 0) {
  5719. for (i = 0; i < len; i += 1) {
  5720. self.cancelling = true;
  5721. xhr[i].abort();
  5722. }
  5723. }
  5724. self._getThumbs().each(function () {
  5725. var $thumb = $(this), $prog = $thumb.find('.file-thumb-progress');
  5726. $thumb.removeClass('file-uploading');
  5727. self._setProgress(0, $prog);
  5728. $prog.hide();
  5729. if (!self._getThumbFile($thumb)) {
  5730. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  5731. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5732. }
  5733. self.unlock();
  5734. });
  5735. setTimeout(function () {
  5736. self._setProgressCancelled();
  5737. }, self.processDelay);
  5738. return self.$element;
  5739. },
  5740. clear: function () {
  5741. var self = this, cap;
  5742. if (!self._raise('fileclear')) {
  5743. return;
  5744. }
  5745. self.$btnUpload.removeAttr('disabled');
  5746. self._getThumbs().find('video,audio,img').each(function () {
  5747. $h.cleanMemory($(this));
  5748. });
  5749. self._clearFileInput();
  5750. self._resetUpload();
  5751. self.clearFileStack();
  5752. self.isDuplicateError = false;
  5753. self.isPersistentError = false;
  5754. self._resetErrors(true);
  5755. if (self._hasInitialPreview()) {
  5756. self._showFileIcon();
  5757. self._resetPreview();
  5758. self._initPreviewActions();
  5759. self.$container.removeClass('file-input-new');
  5760. } else {
  5761. self._getThumbs().each(function () {
  5762. self._clearObjects($(this));
  5763. });
  5764. if (self.isAjaxUpload) {
  5765. self.previewCache.data = {};
  5766. }
  5767. self.$preview.html('');
  5768. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  5769. self.$caption.attr('title', '').val(cap);
  5770. $h.addCss(self.$container, 'file-input-new');
  5771. self._validateDefaultPreview();
  5772. }
  5773. if (self.$container.find($h.FRAMES).length === 0) {
  5774. if (!self._initCaption()) {
  5775. self.$captionContainer.removeClass('icon-visible');
  5776. }
  5777. }
  5778. self._hideFileIcon();
  5779. if (self.focusCaptionOnClear) {
  5780. self.$captionContainer.focus();
  5781. }
  5782. self._setFileDropZoneTitle();
  5783. self._raise('filecleared');
  5784. return self.$element;
  5785. },
  5786. reset: function () {
  5787. var self = this;
  5788. if (!self._raise('filereset')) {
  5789. return;
  5790. }
  5791. self.lastProgress = 0;
  5792. self._resetPreview();
  5793. self.$container.find('.fileinput-filename').text('');
  5794. $h.addCss(self.$container, 'file-input-new');
  5795. if (self.getFrames().length) {
  5796. self.$container.removeClass('file-input-new');
  5797. }
  5798. self.clearFileStack();
  5799. self._setFileDropZoneTitle();
  5800. return self.$element;
  5801. },
  5802. disable: function () {
  5803. var self = this, $container = self.$container;
  5804. self.isDisabled = true;
  5805. self._raise('filedisabled');
  5806. self.$element.attr('disabled', 'disabled');
  5807. $container.addClass('is-locked');
  5808. $h.addCss($container.find('.btn-file'), 'disabled');
  5809. $container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  5810. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5811. .attr('disabled', true);
  5812. self._initDragDrop();
  5813. return self.$element;
  5814. },
  5815. enable: function () {
  5816. var self = this, $container = self.$container;
  5817. self.isDisabled = false;
  5818. self._raise('fileenabled');
  5819. self.$element.removeAttr('disabled');
  5820. $container.removeClass('is-locked');
  5821. $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  5822. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5823. .removeAttr('disabled');
  5824. $container.find('.btn-file').removeClass('disabled');
  5825. self._initDragDrop();
  5826. return self.$element;
  5827. },
  5828. upload: function () {
  5829. var self = this, fm = self.fileManager, totLen = fm.count(), i, outData,
  5830. hasExtraData = !$.isEmptyObject(self._getExtraData());
  5831. fm.bpsLog = [];
  5832. fm.bps = 0;
  5833. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  5834. return;
  5835. }
  5836. self.lastProgress = 0;
  5837. self._resetUpload();
  5838. if (totLen === 0 && !hasExtraData) {
  5839. self._showFileError(self.msgUploadEmpty);
  5840. return;
  5841. }
  5842. self.cancelling = false;
  5843. self._showProgress();
  5844. self.lock();
  5845. if (totLen === 0 && hasExtraData) {
  5846. self._setProgress(2);
  5847. self._uploadExtraOnly();
  5848. return;
  5849. }
  5850. if (self.enableResumableUpload) {
  5851. return self.resume();
  5852. }
  5853. if (self.uploadAsync || self.enableResumableUpload) {
  5854. outData = self._getOutData(null);
  5855. if (!self._checkBatchPreupload(outData)) {
  5856. return;
  5857. }
  5858. self.fileBatchCompleted = false;
  5859. self.uploadCache = [];
  5860. $.each(self.getFileStack(), function (id) {
  5861. var previewId = self._getThumbId(id);
  5862. self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true});
  5863. });
  5864. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  5865. self._initSortable();
  5866. }
  5867. self._setProgress(2);
  5868. self.hasInitData = false;
  5869. if (self.uploadAsync) {
  5870. i = 0;
  5871. $.each(self.getFileStack(), function (id) {
  5872. self._uploadSingle(i, id, true);
  5873. i++;
  5874. });
  5875. return;
  5876. }
  5877. self._uploadBatch();
  5878. return self.$element;
  5879. },
  5880. destroy: function () {
  5881. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  5882. $(document).off(ns);
  5883. $(window).off(ns);
  5884. if ($form && $form.length) {
  5885. $form.off(ns);
  5886. }
  5887. if (self.isAjaxUpload) {
  5888. self._clearFileInput();
  5889. }
  5890. self._cleanup();
  5891. self._initPreviewCache();
  5892. $el.insertBefore($cont).off(ns).removeData();
  5893. $cont.off().remove();
  5894. return $el;
  5895. },
  5896. refresh: function (options) {
  5897. var self = this, $el = self.$element;
  5898. if (typeof options !== 'object' || $h.isEmpty(options)) {
  5899. options = self.options;
  5900. } else {
  5901. options = $.extend(true, {}, self.options, options);
  5902. }
  5903. self._init(options, true);
  5904. self._listen();
  5905. return $el;
  5906. },
  5907. zoom: function (frameId) {
  5908. var self = this, $frame = self._getFrame(frameId);
  5909. self._showModal($frame);
  5910. },
  5911. getExif: function (frameId) {
  5912. var self = this, $frame = self._getFrame(frameId);
  5913. return $frame && $frame.data('exif') || null;
  5914. },
  5915. getFrames: function (cssFilter) {
  5916. var self = this, $frames;
  5917. cssFilter = cssFilter || '';
  5918. $frames = self.$preview.find($h.FRAMES + cssFilter);
  5919. if (self.reversePreviewOrder) {
  5920. $frames = $($frames.get().reverse());
  5921. }
  5922. return $frames;
  5923. },
  5924. getPreview: function () {
  5925. var self = this;
  5926. return {
  5927. content: self.initialPreview,
  5928. config: self.initialPreviewConfig,
  5929. tags: self.initialPreviewThumbTags
  5930. };
  5931. }
  5932. };
  5933. $.fn.fileinput = function (option) {
  5934. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  5935. return;
  5936. }
  5937. var args = Array.apply(null, arguments), retvals = [];
  5938. args.shift();
  5939. this.each(function () {
  5940. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  5941. theme = options.theme || self.data('theme'), l = {}, t = {},
  5942. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  5943. if (!data) {
  5944. if (theme) {
  5945. t = $.fn.fileinputThemes[theme] || {};
  5946. }
  5947. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  5948. l = $.fn.fileinputLocales[lang] || {};
  5949. }
  5950. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  5951. data = new FileInput(this, opt);
  5952. self.data('fileinput', data);
  5953. }
  5954. if (typeof option === 'string') {
  5955. retvals.push(data[option].apply(data, args));
  5956. }
  5957. });
  5958. switch (retvals.length) {
  5959. case 0:
  5960. return this;
  5961. case 1:
  5962. return retvals[0];
  5963. default:
  5964. return retvals;
  5965. }
  5966. };
  5967. var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}',
  5968. defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss(), defBtnCss2 = 'btn ' + $h.defaultButtonCss(true);
  5969. $.fn.fileinput.defaults = {
  5970. language: 'zh',
  5971. bytesToKB: 1024,
  5972. showCaption: true,
  5973. showBrowse: true,
  5974. showPreview: true,
  5975. showRemove: true,
  5976. showUpload: true,
  5977. showUploadStats: true,
  5978. showCancel: null,
  5979. showPause: null,
  5980. showClose: true,
  5981. showUploadedThumbs: true,
  5982. showConsoleLogs: false,
  5983. browseOnZoneClick: false,
  5984. autoReplace: false,
  5985. showDescriptionClose: true,
  5986. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  5987. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  5988. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  5989. return !iOSSafari;
  5990. },
  5991. autoOrientImageInitial: true,
  5992. required: false,
  5993. rtl: false,
  5994. hideThumbnailContent: false,
  5995. encodeUrl: true,
  5996. focusCaptionOnBrowse: true,
  5997. focusCaptionOnClear: true,
  5998. generateFileId: null,
  5999. previewClass: '',
  6000. captionClass: '',
  6001. frameClass: 'krajee-default',
  6002. mainClass: '',
  6003. inputGroupClass: '',
  6004. mainTemplate: null,
  6005. fileSizeGetter: null,
  6006. initialCaption: '',
  6007. initialPreview: [],
  6008. initialPreviewDelimiter: '*$$*',
  6009. initialPreviewAsData: false,
  6010. initialPreviewFileType: 'image',
  6011. initialPreviewConfig: [],
  6012. initialPreviewThumbTags: [],
  6013. previewThumbTags: {},
  6014. initialPreviewShowDelete: true,
  6015. initialPreviewDownloadUrl: '',
  6016. removeFromPreviewOnError: false,
  6017. deleteUrl: '',
  6018. deleteExtraData: {},
  6019. overwriteInitial: true,
  6020. sanitizeZoomCache: function (content) {
  6021. var $container = $h.createElement(content);
  6022. $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove();
  6023. return $container.html();
  6024. },
  6025. previewZoomButtonIcons: {
  6026. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  6027. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  6028. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  6029. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  6030. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  6031. close: '<i class="glyphicon glyphicon-remove"></i>'
  6032. },
  6033. previewZoomButtonClasses: {
  6034. prev: 'btn btn-default btn-outline-secondary btn-navigate',
  6035. next: 'btn btn-default btn-outline-secondary btn-navigate',
  6036. toggleheader: defBtnCss1,
  6037. fullscreen: defBtnCss1,
  6038. borderless: defBtnCss1,
  6039. close: defBtnCss1
  6040. },
  6041. previewTemplates: {},
  6042. previewContentTemplates: {},
  6043. preferIconicPreview: false,
  6044. preferIconicZoomPreview: false,
  6045. allowedFileTypes: null,
  6046. allowedFileExtensions: null,
  6047. allowedPreviewTypes: undefined,
  6048. allowedPreviewMimeTypes: null,
  6049. allowedPreviewExtensions: null,
  6050. disabledPreviewTypes: undefined,
  6051. disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'],
  6052. disabledPreviewMimeTypes: null,
  6053. defaultPreviewContent: null,
  6054. customLayoutTags: {},
  6055. customPreviewTags: {},
  6056. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  6057. previewFileIconClass: 'file-other-icon',
  6058. previewFileIconSettings: {},
  6059. previewFileExtSettings: {},
  6060. buttonLabelClass: 'hidden-xs',
  6061. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  6062. browseClass: 'btn btn-primary',
  6063. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  6064. removeClass: defBtnCss2,
  6065. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  6066. cancelClass: defBtnCss2,
  6067. pauseIcon: '<i class="glyphicon glyphicon-pause"></i>',
  6068. pauseClass: defBtnCss2,
  6069. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  6070. uploadClass: defBtnCss2,
  6071. uploadUrl: null,
  6072. uploadUrlThumb: null,
  6073. uploadAsync: true,
  6074. uploadParamNames: {
  6075. chunkCount: 'chunkCount',
  6076. chunkIndex: 'chunkIndex',
  6077. chunkSize: 'chunkSize',
  6078. chunkSizeStart: 'chunkSizeStart',
  6079. chunksUploaded: 'chunksUploaded',
  6080. fileBlob: 'fileBlob',
  6081. fileId: 'fileId',
  6082. fileName: 'fileName',
  6083. fileRelativePath: 'fileRelativePath',
  6084. fileSize: 'fileSize',
  6085. retryCount: 'retryCount'
  6086. },
  6087. maxAjaxThreads: 5,
  6088. fadeDelay: 800,
  6089. processDelay: 100,
  6090. bitrateUpdateDelay: 500,
  6091. queueDelay: 10, // must be lesser than process delay
  6092. progressDelay: 0, // must be lesser than process delay
  6093. enableResumableUpload: false,
  6094. resumableUploadOptions: {
  6095. fallback: null,
  6096. testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
  6097. chunkSize: 2048, // in KB
  6098. maxThreads: 4,
  6099. maxRetries: 3,
  6100. showErrorLog: true,
  6101. retainErrorHistory: true, // display complete error history always unless user explicitly resets upload
  6102. skipErrorsAndProceed: false // when set to true, files with errors will be skipped and upload will continue with other files
  6103. },
  6104. uploadExtraData: {},
  6105. zoomModalHeight: 480,
  6106. minImageWidth: null,
  6107. minImageHeight: null,
  6108. maxImageWidth: null,
  6109. maxImageHeight: null,
  6110. resizeImage: false,
  6111. resizePreference: 'width',
  6112. resizeQuality: 0.92,
  6113. resizeDefaultImageType: 'image/jpeg',
  6114. resizeIfSizeMoreThan: 0, // in KB
  6115. minFileSize: -1,
  6116. maxFileSize: 0,
  6117. maxFilePreviewSize: 25600, // 25 MB
  6118. minFileCount: 0,
  6119. maxFileCount: 0,
  6120. maxTotalFileCount: 0,
  6121. validateInitialCount: false,
  6122. msgValidationErrorClass: 'text-danger',
  6123. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  6124. msgErrorClass: 'file-error-message',
  6125. progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated',
  6126. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated',
  6127. progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated',
  6128. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  6129. progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated',
  6130. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  6131. progressUploadThreshold: 99,
  6132. previewFileType: 'image',
  6133. elCaptionContainer: null,
  6134. elCaptionText: null,
  6135. elPreviewContainer: null,
  6136. elPreviewImage: null,
  6137. elPreviewStatus: null,
  6138. elErrorContainer: null,
  6139. errorCloseButton: undefined,
  6140. slugCallback: null,
  6141. dropZoneEnabled: true,
  6142. dropZoneTitleClass: 'file-drop-zone-title',
  6143. fileActionSettings: {},
  6144. otherActionButtons: '',
  6145. textEncoding: 'UTF-8',
  6146. preProcessUpload: null,
  6147. ajaxSettings: {},
  6148. ajaxDeleteSettings: {},
  6149. showAjaxErrorDetails: true,
  6150. mergeAjaxCallbacks: false,
  6151. mergeAjaxDeleteCallbacks: false,
  6152. retryErrorUploads: true,
  6153. reversePreviewOrder: false,
  6154. usePdfRenderer: function () {
  6155. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  6156. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  6157. },
  6158. pdfRendererUrl: '',
  6159. pdfRendererTemplate: '<iframe ' + IFRAME_ATTRIBS + '></iframe>',
  6160. tabIndexConfig: {
  6161. browse: 500,
  6162. remove: 500,
  6163. upload: 500,
  6164. cancel: null,
  6165. pause: null,
  6166. modal: -1
  6167. }
  6168. };
  6169. // noinspection HtmlUnknownAttribute
  6170. $.fn.fileinputLocales.en = {
  6171. sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  6172. bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
  6173. fileSingle: 'file',
  6174. filePlural: 'files',
  6175. browseLabel: 'Browse &hellip;',
  6176. removeLabel: 'Remove',
  6177. removeTitle: 'Clear all unprocessed files',
  6178. cancelLabel: 'Cancel',
  6179. cancelTitle: 'Abort ongoing upload',
  6180. pauseLabel: 'Pause',
  6181. pauseTitle: 'Pause ongoing upload',
  6182. uploadLabel: 'Upload',
  6183. uploadTitle: 'Upload selected files',
  6184. msgNo: 'No',
  6185. msgNoFilesSelected: 'No files selected',
  6186. msgCancelled: 'Cancelled',
  6187. msgPaused: 'Paused',
  6188. msgPlaceholder: 'Select {files} ...',
  6189. msgZoomModalHeading: 'Detailed Preview',
  6190. msgFileRequired: 'You must select a file to upload.',
  6191. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  6192. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  6193. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  6194. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  6195. msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).',
  6196. msgFileNotFound: 'File "{name}" not found!',
  6197. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  6198. msgFileNotReadable: 'File "{name}" is not readable.',
  6199. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  6200. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  6201. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  6202. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  6203. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  6204. msgFileTypes: {
  6205. 'image': 'image',
  6206. 'html': 'HTML',
  6207. 'text': 'text',
  6208. 'video': 'video',
  6209. 'audio': 'audio',
  6210. 'flash': 'flash',
  6211. 'pdf': 'PDF',
  6212. 'object': 'object'
  6213. },
  6214. msgUploadAborted: 'The file upload was aborted',
  6215. msgUploadThreshold: 'Processing &hellip;',
  6216. msgUploadBegin: 'Initializing &hellip;',
  6217. msgUploadEnd: 'Done',
  6218. msgUploadResume: 'Resuming upload &hellip;',
  6219. msgUploadEmpty: 'No valid data available for upload.',
  6220. msgUploadError: 'Upload Error',
  6221. msgDeleteError: 'Delete Error',
  6222. msgProgressError: 'Error',
  6223. msgValidationError: 'Validation Error',
  6224. msgLoading: 'Loading file {index} of {files} &hellip;',
  6225. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  6226. msgSelected: '{n} {files} selected',
  6227. msgProcessing: 'Processing ...',
  6228. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  6229. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  6230. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  6231. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  6232. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  6233. msgImageResizeError: 'Could not get the image dimensions to resize.',
  6234. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  6235. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  6236. msgAjaxProgressError: '{operation} failed',
  6237. msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
  6238. msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
  6239. msgPendingTime: '{time} remaining',
  6240. msgCalculatingTime: 'calculating time remaining',
  6241. ajaxOperations: {
  6242. deleteThumb: 'file delete',
  6243. uploadThumb: 'file upload',
  6244. uploadBatch: 'batch file upload',
  6245. uploadExtra: 'form data upload'
  6246. },
  6247. dropZoneTitle: 'Drag & drop files here &hellip;',
  6248. dropZoneClickTitle: '<br>(or click to select {files})',
  6249. previewZoomButtonTitles: {
  6250. prev: 'View previous file',
  6251. next: 'View next file',
  6252. toggleheader: 'Toggle header',
  6253. fullscreen: 'Toggle full screen',
  6254. borderless: 'Toggle borderless mode',
  6255. close: 'Close detailed preview'
  6256. }
  6257. };
  6258. $.fn.fileinputLocales.zh = {
  6259. sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  6260. bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
  6261. fileSingle: '文件',
  6262. filePlural: '个文件',
  6263. browseLabel: '选择 &hellip;',
  6264. removeLabel: '移除',
  6265. removeTitle: '清除选中文件',
  6266. cancelLabel: '取消',
  6267. cancelTitle: '取消进行中的上传',
  6268. pauseLabel: '暂停',
  6269. pauseTitle: '暂停上传',
  6270. uploadLabel: '上传',
  6271. uploadTitle: '上传选中文件',
  6272. msgNo: '没有',
  6273. msgNoFilesSelected: '未选择文件',
  6274. msgPaused: '已暂停',
  6275. msgCancelled: '取消',
  6276. msgPlaceholder: '选择 {files} ...',
  6277. msgZoomModalHeading: '详细预览',
  6278. msgFileRequired: '必须选择一个文件上传.',
  6279. msgSizeTooSmall: '文件 "{name}" (<b>{size} KB</b>) 必须大于限定大小 <b>{minSize} KB</b>.',
  6280. msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
  6281. msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
  6282. msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
  6283. msgTotalFilesTooMany: '你最多可以上传 <b>{m}</b> 个文件 (当前有<b>{n}</b> 个文件).',
  6284. msgFileNotFound: '文件 "{name}" 未找到!',
  6285. msgFileSecured: '安全限制,为了防止读取文件 "{name}".',
  6286. msgFileNotReadable: '文件 "{name}" 不可读.',
  6287. msgFilePreviewAborted: '取消 "{name}" 的预览.',
  6288. msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
  6289. msgInvalidFileName: '文件名 "{name}" 包含非法字符.',
  6290. msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
  6291. msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
  6292. msgFileTypes: {
  6293. 'image': 'image',
  6294. 'html': 'HTML',
  6295. 'text': 'text',
  6296. 'video': 'video',
  6297. 'audio': 'audio',
  6298. 'flash': 'flash',
  6299. 'pdf': 'PDF',
  6300. 'object': 'object'
  6301. },
  6302. msgUploadAborted: '该文件上传被中止',
  6303. msgUploadThreshold: '处理中 &hellip;',
  6304. msgUploadBegin: '正在初始化 &hellip;',
  6305. msgUploadEnd: '完成',
  6306. msgUploadResume: '继续上传 &hellip;',
  6307. msgUploadEmpty: '无效的文件上传.',
  6308. msgUploadError: '上传出错',
  6309. msgDeleteError: '删除出错',
  6310. msgProgressError: '上传出错',
  6311. msgValidationError: '验证错误',
  6312. msgLoading: '加载第 {index} 文件 共 {files} &hellip;',
  6313. msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
  6314. msgSelected: '{n} {files} 选中',
  6315. msgProcessing: '处理中 ...',
  6316. msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
  6317. msgImageWidthSmall: '图像文件的"{name}"的宽度必须是至少{size}像素.',
  6318. msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
  6319. msgImageWidthLarge: '图像文件"{name}"的宽度不能超过{size}像素.',
  6320. msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
  6321. msgImageResizeError: '无法获取的图像尺寸调整。',
  6322. msgImageResizeException: '调整图像大小时发生错误。<pre>{errors}</pre>',
  6323. msgAjaxError: '{operation} 发生错误. 请重试!',
  6324. msgAjaxProgressError: '{operation} 失败',
  6325. msgDuplicateFile: '文件 "{name}",大小 "{size} KB" 已经被选中.忽略相同的文件.',
  6326. msgResumableUploadRetriesExceeded: '文件 <b>{file}</b> 上传失败超过 <b>{max}</b> 次重试 ! 错误详情: <pre>{error}</pre>',
  6327. msgPendingTime: '{time} 剩余',
  6328. msgCalculatingTime: '计算剩余时间',
  6329. ajaxOperations: {
  6330. deleteThumb: '删除文件',
  6331. uploadThumb: '上传文件',
  6332. uploadBatch: '批量上传',
  6333. uploadExtra: '表单数据上传'
  6334. },
  6335. dropZoneTitle: '拖拽文件到这里 &hellip;<br>支持多文件同时上传',
  6336. dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)',
  6337. fileActionSettings: {
  6338. removeTitle: '删除文件',
  6339. uploadTitle: '上传文件',
  6340. downloadTitle: '下载文件',
  6341. uploadRetryTitle: '重试',
  6342. zoomTitle: '查看详情',
  6343. dragTitle: '移动 / 重置',
  6344. indicatorNewTitle: '没有上传',
  6345. indicatorSuccessTitle: '上传',
  6346. indicatorErrorTitle: '上传错误',
  6347. indicatorPausedTitle: '上传已暂停',
  6348. indicatorLoadingTitle: '上传 &hellip;'
  6349. },
  6350. previewZoomButtonTitles: {
  6351. prev: '预览上一个文件',
  6352. next: '预览下一个文件',
  6353. toggleheader: '缩放',
  6354. fullscreen: '全屏',
  6355. borderless: '无边界模式',
  6356. close: '关闭当前预览'
  6357. }
  6358. };
  6359. $.fn.fileinput.Constructor = FileInput;
  6360. /**
  6361. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  6362. */
  6363. $(document).ready(function () {
  6364. var $input = $('input.file[type=file]');
  6365. if ($input.length) {
  6366. $input.fileinput();
  6367. }
  6368. });
  6369. }));