fileinput.js 174 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833
  1. /*!
  2. * bootstrap-fileinput v4.4.0
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2017, 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. //noinspection JSUnresolvedVariable
  14. if (typeof define === 'function' && define.amd) { // jshint ignore:line
  15. // AMD. Register as an anonymous module.
  16. define(['jquery'], factory); // jshint ignore:line
  17. } else { // noinspection JSUnresolvedVariable
  18. if (typeof module === 'object' && module.exports) { // jshint ignore:line
  19. // Node/CommonJS
  20. // noinspection JSUnresolvedVariable
  21. module.exports = factory(require('jquery')); // jshint ignore:line
  22. } else {
  23. // Browser globals
  24. factory(window.jQuery);
  25. }
  26. }
  27. }(function ($) {
  28. "use strict";
  29. $.fn.fileinputLocales = {};
  30. $.fn.fileinputThemes = {};
  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. var $h, FileInput;
  42. // fileinput helper object for all global variables and internal helper methods
  43. //noinspection JSUnresolvedVariable
  44. $h = {
  45. FRAMES: '.kv-preview-thumb',
  46. SORT_CSS: 'file-sortable',
  47. STYLE_SETTING: 'style="width:{width};height:{height};"',
  48. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  49. '<param name="allowFullScreen" value="true" />\n' +
  50. '<param name="allowScriptAccess" value="always" />\n' +
  51. '<param name="autoPlay" value="false" />\n' +
  52. '<param name="autoStart" value="false" />\n' +
  53. '<param name="quality" value="high" />\n',
  54. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  55. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  56. '</div>',
  57. MODAL_ID: 'kvFileinputModal',
  58. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  59. objUrl: window.URL || window.webkitURL,
  60. compare: function (input, str, exact) {
  61. return input !== undefined && (exact ? input === str : input.match(str));
  62. },
  63. isIE: function (ver) {
  64. // check for IE versions < 11
  65. if (navigator.appName !== 'Microsoft Internet Explorer') {
  66. return false;
  67. }
  68. if (ver === 10) {
  69. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  70. }
  71. var div = document.createElement("div"), status;
  72. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  73. status = div.getElementsByTagName("i").length;
  74. document.body.appendChild(div);
  75. div.parentNode.removeChild(div);
  76. return status;
  77. },
  78. initModal: function ($modal) {
  79. var $body = $('body');
  80. if ($body.length) {
  81. $modal.appendTo($body);
  82. }
  83. },
  84. isEmpty: function (value, trim) {
  85. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  86. },
  87. isArray: function (a) {
  88. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  89. },
  90. ifSet: function (needle, haystack, def) {
  91. def = def || '';
  92. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  93. },
  94. cleanArray: function (arr) {
  95. if (!(arr instanceof Array)) {
  96. arr = [];
  97. }
  98. return arr.filter(function (e) {
  99. return (e !== undefined && e !== null);
  100. });
  101. },
  102. spliceArray: function (arr, index) {
  103. var i, j = 0, out = [];
  104. if (!(arr instanceof Array)) {
  105. return [];
  106. }
  107. for (i = 0; i < arr.length; i++) {
  108. if (i !== index) {
  109. out[j] = arr[i];
  110. j++;
  111. }
  112. }
  113. return out;
  114. },
  115. getNum: function (num, def) {
  116. def = def || 0;
  117. if (typeof num === "number") {
  118. return num;
  119. }
  120. if (typeof num === "string") {
  121. num = parseFloat(num);
  122. }
  123. return isNaN(num) ? def : num;
  124. },
  125. hasFileAPISupport: function () {
  126. return !!(window.File && window.FileReader);
  127. },
  128. hasDragDropSupport: function () {
  129. var div = document.createElement('div');
  130. /** @namespace div.draggable */
  131. /** @namespace div.ondragstart */
  132. /** @namespace div.ondrop */
  133. return !$h.isIE(9) &&
  134. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  135. },
  136. hasFileUploadSupport: function () {
  137. return $h.hasFileAPISupport() && window.FormData;
  138. },
  139. addCss: function ($el, css) {
  140. $el.removeClass(css).addClass(css);
  141. },
  142. getElement: function (options, param, value) {
  143. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  144. },
  145. uniqId: function () {
  146. return Math.round(new Date().getTime() + (Math.random() * 100));
  147. },
  148. htmlEncode: function (str) {
  149. return str.replace(/&/g, '&amp;')
  150. .replace(/</g, '&lt;')
  151. .replace(/>/g, '&gt;')
  152. .replace(/"/g, '&quot;')
  153. .replace(/'/g, '&apos;');
  154. },
  155. replaceTags: function (str, tags) {
  156. var out = str;
  157. if (!tags) {
  158. return out;
  159. }
  160. $.each(tags, function (key, value) {
  161. if (typeof value === "function") {
  162. value = value();
  163. }
  164. out = out.split(key).join(value);
  165. });
  166. return out;
  167. },
  168. cleanMemory: function ($thumb) {
  169. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  170. /** @namespace $h.objUrl.revokeObjectURL */
  171. $h.objUrl.revokeObjectURL(data);
  172. },
  173. findFileName: function (filePath) {
  174. var sepIndex = filePath.lastIndexOf('/');
  175. if (sepIndex === -1) {
  176. sepIndex = filePath.lastIndexOf('\\');
  177. }
  178. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  179. },
  180. checkFullScreen: function () {
  181. //noinspection JSUnresolvedVariable
  182. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  183. document.msFullscreenElement;
  184. },
  185. toggleFullScreen: function (maximize) {
  186. var doc = document, de = doc.documentElement;
  187. if (de && maximize && !$h.checkFullScreen()) {
  188. /** @namespace document.requestFullscreen */
  189. /** @namespace document.msRequestFullscreen */
  190. /** @namespace document.mozRequestFullScreen */
  191. /** @namespace document.webkitRequestFullscreen */
  192. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  193. if (de.requestFullscreen) {
  194. de.requestFullscreen();
  195. } else if (de.msRequestFullscreen) {
  196. de.msRequestFullscreen();
  197. } else if (de.mozRequestFullScreen) {
  198. de.mozRequestFullScreen();
  199. } else if (de.webkitRequestFullscreen) {
  200. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  201. }
  202. } else {
  203. /** @namespace document.exitFullscreen */
  204. /** @namespace document.msExitFullscreen */
  205. /** @namespace document.mozCancelFullScreen */
  206. /** @namespace document.webkitExitFullscreen */
  207. if (doc.exitFullscreen) {
  208. doc.exitFullscreen();
  209. } else if (doc.msExitFullscreen) {
  210. doc.msExitFullscreen();
  211. } else if (doc.mozCancelFullScreen) {
  212. doc.mozCancelFullScreen();
  213. } else if (doc.webkitExitFullscreen) {
  214. doc.webkitExitFullscreen();
  215. }
  216. }
  217. },
  218. moveArray: function (arr, oldIndex, newIndex) {
  219. if (newIndex >= arr.length) {
  220. var k = newIndex - arr.length;
  221. while ((k--) + 1) {
  222. arr.push(undefined);
  223. }
  224. }
  225. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  226. return arr;
  227. },
  228. cleanZoomCache: function ($el) {
  229. var $cache = $el.closest('.kv-zoom-cache-theme');
  230. if (!$cache.length) {
  231. $cache = $el.closest('.kv-zoom-cache');
  232. }
  233. $cache.remove();
  234. },
  235. setOrientation: function (buffer, callback) {
  236. var scanner = new DataView(buffer), idx = 0, value = 1, // Non-rotated is the default
  237. maxBytes, uInt16, exifLength;
  238. if (scanner.getUint16(idx) !== 0xFFD8 || buffer.length < 2) {
  239. return; // not a proper JPEG
  240. }
  241. idx += 2;
  242. maxBytes = scanner.byteLength;
  243. while (idx < maxBytes - 2) {
  244. uInt16 = scanner.getUint16(idx);
  245. idx += 2;
  246. switch (uInt16) {
  247. case 0xFFE1: // Start of EXIF
  248. exifLength = scanner.getUint16(idx);
  249. maxBytes = exifLength - idx;
  250. idx += 2;
  251. break;
  252. case 0x0112: // Orientation tag
  253. value = scanner.getUint16(idx + 6, false);
  254. maxBytes = 0; // Stop scanning
  255. break;
  256. }
  257. }
  258. if (callback) {
  259. callback(value);
  260. }
  261. },
  262. validateOrientation: function (file, callback) {
  263. if (!window.FileReader || !window.DataView) {
  264. return; // skip orientation if pre-requisite libraries not supported by browser
  265. }
  266. var reader = new FileReader(), buffer;
  267. reader.onloadend = function () {
  268. buffer = reader.result;
  269. $h.setOrientation(buffer, callback);
  270. };
  271. reader.readAsArrayBuffer(file);
  272. },
  273. adjustOrientedImage: function ($img, isZoom) {
  274. var offsetContTop, offsetTop, newTop;
  275. if (!$img.hasClass('is-portrait-gt4')) {
  276. return;
  277. }
  278. if (isZoom) {
  279. $img.css({width: $img.parent().height()});
  280. return;
  281. } else {
  282. $img.css({height: 'auto', width: $img.height()});
  283. }
  284. offsetContTop = $img.parent().offset().top;
  285. offsetTop = $img.offset().top;
  286. newTop = offsetContTop - offsetTop;
  287. $img.css('margin-top', newTop);
  288. }
  289. };
  290. FileInput = function (element, options) {
  291. var self = this;
  292. self.$element = $(element);
  293. if (!self._validate()) {
  294. return;
  295. }
  296. self.isPreviewable = $h.hasFileAPISupport();
  297. self.isIE9 = $h.isIE(9);
  298. self.isIE10 = $h.isIE(10);
  299. if (self.isPreviewable || self.isIE9) {
  300. self._init(options);
  301. self._listen();
  302. } else {
  303. self.$element.removeClass('file-loading');
  304. }
  305. };
  306. FileInput.prototype = {
  307. constructor: FileInput,
  308. _cleanup: function() {
  309. var self = this;
  310. self.reader = null;
  311. self.formdata = {};
  312. self.uploadCount = 0;
  313. self.uploadStatus = {};
  314. self.uploadLog = [];
  315. self.uploadAsyncCount = 0;
  316. self.loadedImages = [];
  317. self.totalImagesCount = 0;
  318. self.ajaxRequests = [];
  319. self.clearStack();
  320. self.fileInputCleared = false;
  321. self.fileBatchCompleted = true;
  322. if (!self.isPreviewable) {
  323. self.showPreview = false;
  324. }
  325. self.isError = false;
  326. self.ajaxAborted = false;
  327. self.cancelling = false;
  328. },
  329. _init: function (options) {
  330. var self = this, $el = self.$element, $cont, t;
  331. self.options = options;
  332. $.each(options, function (key, value) {
  333. switch (key) {
  334. case 'minFileCount':
  335. case 'maxFileCount':
  336. case 'minFileSize':
  337. case 'maxFileSize':
  338. case 'maxFilePreviewSize':
  339. case 'resizeImageQuality':
  340. case 'resizeIfSizeMoreThan':
  341. case 'progressUploadThreshold':
  342. case 'initialPreviewCount':
  343. case 'zoomModalHeight':
  344. case 'minImageHeight':
  345. case 'maxImageHeight':
  346. case 'minImageWidth':
  347. case 'maxImageWidth':
  348. self[key] = $h.getNum(value);
  349. break;
  350. default:
  351. self[key] = value;
  352. break;
  353. }
  354. });
  355. self._cleanup();
  356. self.$form = $el.closest('form');
  357. self._initTemplateDefaults();
  358. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  359. t = self._getLayoutTemplate('progress');
  360. self.progressTemplate = t.replace('{class}', self.progressClass);
  361. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  362. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  363. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  364. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  365. if (self.isDisabled) {
  366. $el.attr('disabled', true);
  367. }
  368. self.isUploadable = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  369. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  370. (self.isUploadable && self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  371. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  372. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  373. self.captionTemplate = self._getLayoutTemplate('caption');
  374. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  375. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  376. self.imageCanvas = document.createElement('canvas');
  377. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  378. }
  379. if ($h.isEmpty($el.attr('id'))) {
  380. $el.attr('id', $h.uniqId());
  381. }
  382. self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
  383. if (self.$container === undefined) {
  384. self.$container = self._createContainer();
  385. } else {
  386. self._refreshContainer();
  387. }
  388. $cont = self.$container;
  389. self.$dropZone = $cont.find('.file-drop-zone');
  390. self.$progress = $cont.find('.kv-upload-progress');
  391. self.$btnUpload = $cont.find('.fileinput-upload');
  392. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
  393. self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
  394. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
  395. self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
  396. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
  397. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  398. self.$previewContainer.find('.kv-fileinput-error'));
  399. if (!$h.isEmpty(self.msgErrorClass)) {
  400. $h.addCss(self.$errorContainer, self.msgErrorClass);
  401. }
  402. self.$errorContainer.hide();
  403. self.previewInitId = "preview-" + $h.uniqId();
  404. self._initPreviewCache();
  405. self._initPreview(true);
  406. self._initPreviewActions();
  407. self._setFileDropZoneTitle();
  408. $el.removeClass('file-loading');
  409. if ($el.attr('disabled')) {
  410. self.disable();
  411. }
  412. self._initZoom();
  413. },
  414. _initTemplateDefaults: function () {
  415. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  416. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionZoom,
  417. tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage, tText, tVideo,
  418. tAudio, tFlash, tObject, tPdf, tOther, tZoomCache, vDefaultDim;
  419. tMain1 = '{preview}\n' +
  420. '<div class="kv-upload-progress hide"></div>\n' +
  421. '<div class="input-group {class}">\n' +
  422. ' {caption}\n' +
  423. ' <div class="input-group-btn">\n' +
  424. ' {remove}\n' +
  425. ' {cancel}\n' +
  426. ' {upload}\n' +
  427. ' {browse}\n' +
  428. ' </div>\n' +
  429. '</div>';
  430. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  431. tPreview = '<div class="file-preview {class}">\n' +
  432. ' {close}' +
  433. ' <div class="{dropClass}">\n' +
  434. ' <div class="file-preview-thumbnails">\n' +
  435. ' </div>\n' +
  436. ' <div class="clearfix"></div>' +
  437. ' <div class="file-preview-status text-center text-success"></div>\n' +
  438. ' <div class="kv-fileinput-error"></div>\n' +
  439. ' </div>\n' +
  440. '</div>';
  441. tClose = '<div class="close fileinput-remove">&times;</div>\n';
  442. tFileIcon = '<i class="glyphicon glyphicon-file kv-caption-icon"></i>';
  443. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  444. ' <div class="file-caption-name"></div>\n' +
  445. '</div>\n';
  446. //noinspection HtmlUnknownAttribute
  447. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" ' +
  448. '{status}>{icon} {label}</button>';
  449. //noinspection HtmlUnknownAttribute
  450. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  451. //noinspection HtmlUnknownAttribute
  452. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  453. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  454. 'tabindex="-1" aria-labelledby="' + $h.MODAL_ID + 'Label"></div>';
  455. tModal = '<div class="modal-dialog modal-lg" role="document">\n' +
  456. ' <div class="modal-content">\n' +
  457. ' <div class="modal-header">\n' +
  458. ' <div class="kv-zoom-actions pull-right">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  459. ' <h3 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h3>\n' +
  460. ' </div>\n' +
  461. ' <div class="modal-body">\n' +
  462. ' <div class="floating-buttons"></div>\n' +
  463. ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
  464. ' </div>\n' +
  465. ' </div>\n' +
  466. '</div>\n';
  467. tProgress = '<div class="progress">\n' +
  468. ' <div class="{class}" role="progressbar"' +
  469. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  470. ' {status}\n' +
  471. ' </div>\n' +
  472. '</div>';
  473. tSize = ' <samp>({sizeText})</samp>';
  474. tFooter = '<div class="file-thumbnail-footer">\n' +
  475. ' <div class="file-footer-caption" title="{caption}">{caption}<br>{size}</div>\n' +
  476. ' {progress} {indicator} {actions}\n' +
  477. '</div>';
  478. tActions = '{drag}\n' +
  479. '<div class="file-actions">\n' +
  480. ' <div class="file-footer-buttons">\n' +
  481. ' {upload} {delete} {zoom} {other}' +
  482. ' </div>\n' +
  483. ' <div class="clearfix"></div>\n' +
  484. '</div>';
  485. //noinspection HtmlUnknownAttribute
  486. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  487. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  488. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  489. '{uploadIcon}</button>';
  490. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  491. 'title="{zoomTitle}">{zoomIcon}</button>';
  492. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  493. tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
  494. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  495. ' data-template="{template}"';
  496. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  497. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  498. tTagAft = '</div>{footer}\n</div>\n';
  499. tGeneric = '{content}\n';
  500. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" ' + $h.STYLE_SETTING +
  501. '>{data}</div>\n';
  502. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{caption}" alt="{caption}" ' +
  503. $h.STYLE_SETTING + '>\n';
  504. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly ' +
  505. $h.STYLE_SETTING + '>{data}</textarea>\n';
  506. tVideo = '<video class="kv-preview-data file-preview-video" width="{width}" ' +
  507. 'height="{height}" controls>\n' + '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW +
  508. '\n</video>\n';
  509. tAudio = '<div class="file-preview-audio"><audio class="kv-preview-data" controls>\n<source src="{data}" ' +
  510. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio></div>\n';
  511. tFlash = '<object class="kv-preview-data file-object" type="application/x-shockwave-flash" ' +
  512. 'width="{width}" height="{height}" data="{data}">\n' + $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW +
  513. '\n</object>\n';
  514. tObject = '<object class="kv-preview-data file-object {typeCss}" data="{data}" type="{type}" ' +
  515. 'width="{width}" height="{height}">\n' + '<param name="movie" value="{caption}" />\n' +
  516. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  517. tPdf = '<embed class="kv-preview-data" src="{data}" ' +
  518. 'width="{width}" height="{height}" type="application/pdf">\n';
  519. tOther = '<div class="kv-preview-data file-preview-other-frame">\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  520. tZoomCache = '<div class="kv-zoom-cache" style="display:none">{zoomContent}</div>';
  521. vDefaultDim = {width: "100%", height: "100%", 'min-height': "480px"};
  522. self.defaults = {
  523. layoutTemplates: {
  524. main1: tMain1,
  525. main2: tMain2,
  526. preview: tPreview,
  527. close: tClose,
  528. fileIcon: tFileIcon,
  529. caption: tCaption,
  530. modalMain: tModalMain,
  531. modal: tModal,
  532. progress: tProgress,
  533. size: tSize,
  534. footer: tFooter,
  535. indicator: tIndicator,
  536. actions: tActions,
  537. actionDelete: tActionDelete,
  538. actionUpload: tActionUpload,
  539. actionZoom: tActionZoom,
  540. actionDrag: tActionDrag,
  541. btnDefault: tBtnDefault,
  542. btnLink: tBtnLink,
  543. btnBrowse: tBtnBrowse,
  544. zoomCache: tZoomCache
  545. },
  546. previewMarkupTags: {
  547. tagBefore1: tTagBef1,
  548. tagBefore2: tTagBef2,
  549. tagAfter: tTagAft
  550. },
  551. previewContentTemplates: {
  552. generic: tGeneric,
  553. html: tHtml,
  554. image: tImage,
  555. text: tText,
  556. video: tVideo,
  557. audio: tAudio,
  558. flash: tFlash,
  559. object: tObject,
  560. pdf: tPdf,
  561. other: tOther
  562. },
  563. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  564. previewTemplates: {},
  565. previewSettings: {
  566. image: {width: "auto", height: "160px"},
  567. html: {width: "213px", height: "160px"},
  568. text: {width: "213px", height: "160px"},
  569. video: {width: "auto", height: "100%", 'max-width': "100%"},
  570. audio: {width: "100%", height: "30px"},
  571. flash: {width: "auto", height: "100%", 'max-width': "100%"},
  572. object: {height: "100%"},
  573. pdf: {width: "160px", height: "160px"},
  574. other: {width: "160px", height: "160px"}
  575. },
  576. previewZoomSettings: {
  577. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  578. html: vDefaultDim,
  579. text: vDefaultDim,
  580. video: {width: "auto", height: "100%", 'max-width': "100%"},
  581. audio: {width: "100%", height: "30px"},
  582. flash: {width: "auto", height: "480px"},
  583. object: {width: "auto", height: "100%", 'max-width': "100%", 'min-height': "480px"},
  584. pdf: vDefaultDim,
  585. other: {width: "auto", height: "100%", 'min-height': "480px"}
  586. },
  587. fileTypeSettings: {
  588. image: function (vType, vName) {
  589. return $h.compare(vType, 'image.*') || $h.compare(vName, /\.(gif|png|jpe?g)$/i);
  590. },
  591. html: function (vType, vName) {
  592. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  593. },
  594. text: function (vType, vName) {
  595. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  596. $h.compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  597. },
  598. video: function (vType, vName) {
  599. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  600. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  601. },
  602. audio: function (vType, vName) {
  603. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  604. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  605. },
  606. flash: function (vType, vName) {
  607. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, /\.(swf)$/i);
  608. },
  609. pdf: function (vType, vName) {
  610. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  611. },
  612. object: function () {
  613. return true;
  614. },
  615. other: function () {
  616. return true;
  617. }
  618. },
  619. fileActionSettings: {
  620. showRemove: true,
  621. showUpload: true,
  622. showZoom: true,
  623. showDrag: true,
  624. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  625. removeClass: 'btn btn-xs btn-default',
  626. removeTitle: 'Remove file',
  627. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  628. uploadClass: 'btn btn-xs btn-default',
  629. uploadTitle: 'Upload file',
  630. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  631. zoomClass: 'btn btn-xs btn-default',
  632. zoomTitle: 'View Details',
  633. dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>',
  634. dragClass: 'text-info',
  635. dragTitle: 'Move / Rearrange',
  636. dragSettings: {},
  637. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  638. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  639. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  640. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  641. indicatorNewTitle: 'Not uploaded yet',
  642. indicatorSuccessTitle: 'Uploaded',
  643. indicatorErrorTitle: 'Upload Error',
  644. indicatorLoadingTitle: 'Uploading ...'
  645. }
  646. };
  647. $.each(self.defaults, function (key, setting) {
  648. if (key === 'allowedPreviewTypes') {
  649. if (self.allowedPreviewTypes === undefined) {
  650. self.allowedPreviewTypes = setting;
  651. }
  652. return;
  653. }
  654. self[key] = $.extend(true, {}, setting, self[key]);
  655. });
  656. self._initPreviewTemplates();
  657. },
  658. _initPreviewTemplates: function () {
  659. var self = this, cfg = self.defaults, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  660. $.each(cfg.previewContentTemplates, function (key, value) {
  661. if ($h.isEmpty(self.previewTemplates[key])) {
  662. tagBef = tags.tagBefore2;
  663. if (key === 'generic' || key === 'image' || key === 'html' || key === 'text') {
  664. tagBef = tags.tagBefore1;
  665. }
  666. self.previewTemplates[key] = tagBef + value + tagAft;
  667. }
  668. });
  669. },
  670. _initPreviewCache: function () {
  671. var self = this;
  672. self.previewCache = {
  673. data: {},
  674. init: function () {
  675. var content = self.initialPreview;
  676. if (content.length > 0 && !$h.isArray(content)) {
  677. content = content.split(self.initialPreviewDelimiter);
  678. }
  679. self.previewCache.data = {
  680. content: content,
  681. config: self.initialPreviewConfig,
  682. tags: self.initialPreviewThumbTags
  683. };
  684. },
  685. fetch: function () {
  686. return self.previewCache.data.content.filter(function (n) {
  687. return n !== null;
  688. });
  689. },
  690. count: function (all) {
  691. return !!self.previewCache.data && !!self.previewCache.data.content ?
  692. (all ? self.previewCache.data.content.length : self.previewCache.fetch().length) : 0;
  693. },
  694. get: function (i, isDisabled) {
  695. var ind = 'init_' + i, data = self.previewCache.data, config = data.config[i],
  696. content = data.content[i], previewId = self.previewInitId + '-' + ind, out, $tmp, cat, ftr,
  697. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  698. parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) {
  699. fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : '');
  700. return self._generatePreviewTemplate(cat, dat, fn, ft, id, false, null, fc, ftr, ind, t);
  701. };
  702. if (!content) {
  703. return '';
  704. }
  705. isDisabled = isDisabled === undefined ? true : isDisabled;
  706. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  707. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  708. ftype = $h.ifSet('filetype', config, cat);
  709. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  710. frameClass = $h.ifSet('frameClass', config);
  711. if (asData) {
  712. out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass);
  713. } else {
  714. out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat)
  715. .setTokens({'content': data.content[i]});
  716. }
  717. if (data.tags.length && data.tags[i]) {
  718. out = $h.replaceTags(out, data.tags[i]);
  719. }
  720. /** @namespace config.frameAttr */
  721. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  722. $tmp = $(document.createElement('div')).html(out);
  723. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  724. out = $tmp.html();
  725. $tmp.remove();
  726. }
  727. return out;
  728. },
  729. add: function (content, config, tags, append) {
  730. var data = self.previewCache.data, index;
  731. if (!$h.isArray(content)) {
  732. content = content.split(self.initialPreviewDelimiter);
  733. }
  734. if (append) {
  735. index = data.content.push(content) - 1;
  736. data.config[index] = config;
  737. data.tags[index] = tags;
  738. } else {
  739. index = content.length - 1;
  740. data.content = content;
  741. data.config = config;
  742. data.tags = tags;
  743. }
  744. self.previewCache.data = data;
  745. return index;
  746. },
  747. set: function (content, config, tags, append) {
  748. var data = self.previewCache.data, i, chk;
  749. if (!content || !content.length) {
  750. return;
  751. }
  752. if (!$h.isArray(content)) {
  753. content = content.split(self.initialPreviewDelimiter);
  754. }
  755. chk = content.filter(function (n) {
  756. return n !== null;
  757. });
  758. if (!chk.length) {
  759. return;
  760. }
  761. if (data.content === undefined) {
  762. data.content = [];
  763. }
  764. if (data.config === undefined) {
  765. data.config = [];
  766. }
  767. if (data.tags === undefined) {
  768. data.tags = [];
  769. }
  770. if (append) {
  771. for (i = 0; i < content.length; i++) {
  772. if (content[i]) {
  773. data.content.push(content[i]);
  774. }
  775. }
  776. for (i = 0; i < config.length; i++) {
  777. if (config[i]) {
  778. data.config.push(config[i]);
  779. }
  780. }
  781. for (i = 0; i < tags.length; i++) {
  782. if (tags[i]) {
  783. data.tags.push(tags[i]);
  784. }
  785. }
  786. } else {
  787. data.content = content;
  788. data.config = config;
  789. data.tags = tags;
  790. }
  791. self.previewCache.data = data;
  792. },
  793. unset: function (index) {
  794. var chk = self.previewCache.count();
  795. if (!chk) {
  796. return;
  797. }
  798. if (chk === 1) {
  799. self.previewCache.data.content = [];
  800. self.previewCache.data.config = [];
  801. self.previewCache.data.tags = [];
  802. self.initialPreview = [];
  803. self.initialPreviewConfig = [];
  804. self.initialPreviewThumbTags = [];
  805. return;
  806. }
  807. self.previewCache.data.content[index] = null;
  808. self.previewCache.data.config[index] = null;
  809. self.previewCache.data.tags[index] = null;
  810. },
  811. out: function () {
  812. var html = '', caption, len = self.previewCache.count(true), i;
  813. if (len === 0) {
  814. return {content: '', caption: ''};
  815. }
  816. for (i = 0; i < len; i++) {
  817. html += self.previewCache.get(i);
  818. }
  819. caption = self._getMsgSelected(self.previewCache.count());
  820. return {content: html, caption: caption};
  821. },
  822. footer: function (i, isDisabled, size) {
  823. var data = self.previewCache.data;
  824. if (!data || !data.config || data.config.length === 0 || $h.isEmpty(data.config[i])) {
  825. return '';
  826. }
  827. isDisabled = isDisabled === undefined ? true : isDisabled;
  828. var config = data.config[i], caption = $h.ifSet('caption', config), actions,
  829. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  830. key = $h.ifSet('key', config, null), fs = self.fileActionSettings,
  831. initPreviewShowDel = self.initialPreviewShowDelete || false,
  832. showDel = $h.ifSet('showDelete', config, $h.ifSet('showDelete', fs, initPreviewShowDel)),
  833. showZoom = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  834. showDrag = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  835. disabled = (url === false) && isDisabled;
  836. actions = self._renderFileActions(false, showDel, showZoom, showDrag, disabled, url, key, true);
  837. return self._getLayoutTemplate('footer').setTokens({
  838. 'progress': self._renderThumbProgress(),
  839. 'actions': actions,
  840. 'caption': caption,
  841. 'size': self._getSize(size),
  842. 'width': width,
  843. 'indicator': ''
  844. });
  845. }
  846. };
  847. self.previewCache.init();
  848. },
  849. _handler: function ($el, event, callback) {
  850. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  851. if (!$el || !$el.length) {
  852. return;
  853. }
  854. $el.off(ev).on(ev, callback);
  855. },
  856. _log: function (msg) {
  857. var self = this, id = self.$element.attr('id');
  858. if (id) {
  859. msg = '"' + id + '": ' + msg;
  860. }
  861. if (typeof window.console.log !== "undefined") {
  862. window.console.log(msg);
  863. } else {
  864. window.alert(msg);
  865. }
  866. },
  867. _validate: function () {
  868. var self = this, status = self.$element.attr('type') === 'file';
  869. if (!status) {
  870. self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.');
  871. }
  872. return status;
  873. },
  874. _errorsExist: function () {
  875. var self = this, $err;
  876. if (self.$errorContainer.find('li').length) {
  877. return true;
  878. }
  879. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  880. $err.find('span.kv-error-close').remove();
  881. $err.find('ul').remove();
  882. return $.trim($err.text()).length ? true : false;
  883. },
  884. _errorHandler: function (evt, caption) {
  885. var self = this, err = evt.target.error, showError = function (msg) {
  886. self._showError(msg.replace('{name}', caption));
  887. };
  888. /** @namespace err.NOT_FOUND_ERR */
  889. /** @namespace err.SECURITY_ERR */
  890. /** @namespace err.NOT_READABLE_ERR */
  891. if (err.code === err.NOT_FOUND_ERR) {
  892. showError(self.msgFileNotFound);
  893. } else if (err.code === err.SECURITY_ERR) {
  894. showError(self.msgFileSecured);
  895. } else if (err.code === err.NOT_READABLE_ERR) {
  896. showError(self.msgFileNotReadable);
  897. } else if (err.code === err.ABORT_ERR) {
  898. showError(self.msgFilePreviewAborted);
  899. } else {
  900. showError(self.msgFilePreviewError);
  901. }
  902. },
  903. _addError: function (msg) {
  904. var self = this, $error = self.$errorContainer;
  905. if (msg && $error.length) {
  906. $error.html(self.errorCloseButton + msg);
  907. self._handler($error.find('.kv-error-close'), 'click', function () {
  908. $error.fadeOut('slow');
  909. });
  910. }
  911. },
  912. _resetErrors: function (fade) {
  913. var self = this, $error = self.$errorContainer;
  914. self.isError = false;
  915. self.$container.removeClass('has-error');
  916. $error.html('');
  917. if (fade) {
  918. $error.fadeOut('slow');
  919. } else {
  920. $error.hide();
  921. }
  922. },
  923. _showFolderError: function (folders) {
  924. var self = this, $error = self.$errorContainer, msg;
  925. if (!folders) {
  926. return;
  927. }
  928. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  929. self._addError(msg);
  930. $h.addCss(self.$container, 'has-error');
  931. $error.fadeIn(800);
  932. self._raise('filefoldererror', [folders, msg]);
  933. },
  934. _showUploadError: function (msg, params, event) {
  935. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  936. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  937. if ($error.find('ul').length === 0) {
  938. self._addError('<ul>' + e + '</ul>');
  939. } else {
  940. $error.find('ul').append(e);
  941. }
  942. $error.fadeIn(800);
  943. self._raise(ev, [params, msg]);
  944. self.$container.removeClass('file-input-new');
  945. $h.addCss(self.$container, 'has-error');
  946. return true;
  947. },
  948. _showError: function (msg, params, event) {
  949. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  950. params = params || {};
  951. params.reader = self.reader;
  952. self._addError(msg);
  953. $error.fadeIn(800);
  954. self._raise(ev, [params, msg]);
  955. if (!self.isUploadable) {
  956. self._clearFileInput();
  957. }
  958. self.$container.removeClass('file-input-new');
  959. $h.addCss(self.$container, 'has-error');
  960. self.$btnUpload.attr('disabled', true);
  961. return true;
  962. },
  963. _noFilesError: function (params) {
  964. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  965. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  966. $error = self.$errorContainer;
  967. self._addError(msg);
  968. self.isError = true;
  969. self._updateFileDetails(0);
  970. $error.fadeIn(800);
  971. self._raise('fileerror', [params, msg]);
  972. self._clearFileInput();
  973. $h.addCss(self.$container, 'has-error');
  974. },
  975. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  976. /** @namespace jqXHR.responseJSON */
  977. var self = this, errMsg = $.trim(errorThrown + ''), dot = errMsg.slice(-1) === '.' ? '' : '.',
  978. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  979. jqXHR.responseJSON.error : jqXHR.responseText;
  980. if (self.cancelling && self.msgUploadAborted) {
  981. errMsg = self.msgUploadAborted;
  982. }
  983. if (self.showAjaxErrorDetails && text) {
  984. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  985. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  986. errMsg += dot + text;
  987. } else {
  988. errMsg += dot;
  989. }
  990. if (errMsg === dot) {
  991. errMsg = self.msgAjaxError.replace('{operation}', operation);
  992. }
  993. self.cancelling = false;
  994. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  995. },
  996. _parseFileType: function (file) {
  997. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  998. for (i = 0; i < types.length; i++) {
  999. cat = types[i];
  1000. isValid = self.fileTypeSettings[cat];
  1001. vType = isValid(file.type, file.name) ? cat : '';
  1002. if (!$h.isEmpty(vType)) {
  1003. return vType;
  1004. }
  1005. }
  1006. return 'other';
  1007. },
  1008. _getPreviewIcon: function (fname) {
  1009. var self = this, ext, out = null;
  1010. if (fname && fname.indexOf('.') > -1) {
  1011. ext = fname.split('.').pop();
  1012. if (self.previewFileIconSettings) {
  1013. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  1014. }
  1015. if (self.previewFileExtSettings) {
  1016. $.each(self.previewFileExtSettings, function (key, func) {
  1017. if (self.previewFileIconSettings[key] && func(ext)) {
  1018. out = self.previewFileIconSettings[key];
  1019. //noinspection UnnecessaryReturnStatementJS
  1020. return;
  1021. }
  1022. });
  1023. }
  1024. }
  1025. return out;
  1026. },
  1027. _parseFilePreviewIcon: function (content, fname) {
  1028. var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon, out = content;
  1029. if (out.indexOf('{previewFileIcon}') > -1) {
  1030. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  1031. }
  1032. return out;
  1033. },
  1034. _raise: function (event, params) {
  1035. var self = this, e = $.Event(event);
  1036. if (params !== undefined) {
  1037. self.$element.trigger(e, params);
  1038. } else {
  1039. self.$element.trigger(e);
  1040. }
  1041. if (e.isDefaultPrevented() || e.result === false) {
  1042. return false;
  1043. }
  1044. switch (event) {
  1045. // ignore these events
  1046. case 'filebatchuploadcomplete':
  1047. case 'filebatchuploadsuccess':
  1048. case 'fileuploaded':
  1049. case 'fileclear':
  1050. case 'filecleared':
  1051. case 'filereset':
  1052. case 'fileerror':
  1053. case 'filefoldererror':
  1054. case 'fileuploaderror':
  1055. case 'filebatchuploaderror':
  1056. case 'filedeleteerror':
  1057. case 'filecustomerror':
  1058. case 'filesuccessremove':
  1059. break;
  1060. // receive data response via `filecustomerror` event`
  1061. default:
  1062. if (!self.ajaxAborted) {
  1063. self.ajaxAborted = e.result;
  1064. }
  1065. break;
  1066. }
  1067. return true;
  1068. },
  1069. _listenFullScreen: function (isFullScreen) {
  1070. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  1071. if (!$modal || !$modal.length) {
  1072. return;
  1073. }
  1074. $btnFull = $modal && $modal.find('.btn-fullscreen');
  1075. $btnBord = $modal && $modal.find('.btn-borderless');
  1076. if (!$btnFull.length || !$btnBord.length) {
  1077. return;
  1078. }
  1079. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1080. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1081. if (isFullScreen) {
  1082. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1083. } else {
  1084. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1085. }
  1086. if ($modal.hasClass('file-zoom-fullscreen')) {
  1087. self._maximizeZoomDialog();
  1088. } else {
  1089. if (isFullScreen) {
  1090. self._maximizeZoomDialog();
  1091. } else {
  1092. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1093. }
  1094. }
  1095. },
  1096. _listen: function () {
  1097. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEvents;
  1098. self._handler($el, 'change', $.proxy(self._change, self));
  1099. if (self.showBrowse) {
  1100. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  1101. }
  1102. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  1103. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  1104. self._initDragDrop();
  1105. self._handler($form, 'reset', $.proxy(self.reset, self));
  1106. if (!self.isUploadable) {
  1107. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  1108. }
  1109. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  1110. self._handler($(window), 'resize', function () {
  1111. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  1112. });
  1113. fullScreenEvents = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  1114. self._handler($(document), fullScreenEvents, function () {
  1115. self._listenFullScreen($h.checkFullScreen());
  1116. });
  1117. self._initClickable();
  1118. },
  1119. _initClickable: function () {
  1120. var self = this, $zone;
  1121. if (!self.isClickable) {
  1122. return;
  1123. }
  1124. $zone = self.isUploadable ? self.$dropZone : self.$preview.find('.file-default-preview');
  1125. $h.addCss($zone, 'clickable');
  1126. $zone.attr('tabindex', -1);
  1127. self._handler($zone, 'click', function (e) {
  1128. var $tar = $(e.target);
  1129. if (!$tar.parents('.file-preview-thumbnails').length || $tar.parents('.file-default-preview').length) {
  1130. self.$element.trigger('click');
  1131. $zone.blur();
  1132. }
  1133. });
  1134. },
  1135. _initDragDrop: function () {
  1136. var self = this, $zone = self.$dropZone;
  1137. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  1138. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  1139. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  1140. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  1141. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  1142. }
  1143. },
  1144. _zoneDragDropInit: function (e) {
  1145. e.stopPropagation();
  1146. e.preventDefault();
  1147. },
  1148. _zoneDragEnter: function (e) {
  1149. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  1150. self._zoneDragDropInit(e);
  1151. if (self.isDisabled || !hasFiles) {
  1152. e.originalEvent.dataTransfer.effectAllowed = 'none';
  1153. e.originalEvent.dataTransfer.dropEffect = 'none';
  1154. return;
  1155. }
  1156. $h.addCss(self.$dropZone, 'file-highlighted');
  1157. },
  1158. _zoneDragLeave: function (e) {
  1159. var self = this;
  1160. self._zoneDragDropInit(e);
  1161. if (self.isDisabled) {
  1162. return;
  1163. }
  1164. self.$dropZone.removeClass('file-highlighted');
  1165. },
  1166. _zoneDrop: function (e) {
  1167. var self = this;
  1168. e.preventDefault();
  1169. /** @namespace e.originalEvent.dataTransfer */
  1170. if (self.isDisabled || $h.isEmpty(e.originalEvent.dataTransfer.files)) {
  1171. return;
  1172. }
  1173. self._change(e, 'dragdrop');
  1174. self.$dropZone.removeClass('file-highlighted');
  1175. },
  1176. _uploadClick: function (e) {
  1177. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1178. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  1179. if (e && e.isDefaultPrevented()) {
  1180. return;
  1181. }
  1182. if (!self.isUploadable) {
  1183. if (isEnabled && $btn.attr('type') !== 'submit') {
  1184. $form = $btn.closest('form');
  1185. // downgrade to normal form submit if possible
  1186. if ($form.length) {
  1187. $form.trigger('submit');
  1188. }
  1189. e.preventDefault();
  1190. }
  1191. return;
  1192. }
  1193. e.preventDefault();
  1194. if (isEnabled) {
  1195. self.upload();
  1196. }
  1197. },
  1198. _submitForm: function () {
  1199. var self = this, $el = self.$element, files = $el.get(0).files;
  1200. if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) {
  1201. self._noFilesError({});
  1202. return false;
  1203. }
  1204. return !self._abort({});
  1205. },
  1206. _clearPreview: function () {
  1207. var self = this, $p = self.$preview,
  1208. $thumbs = self.showUploadedThumbs ? $p.find($h.FRAMES + ':not(.file-preview-success)') : $p.find($h.FRAMES);
  1209. $thumbs.each(function () {
  1210. var $thumb = $(this);
  1211. $thumb.remove();
  1212. $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id')));
  1213. });
  1214. if (!self.$preview.find($h.FRAMES).length || !self.showPreview) {
  1215. self._resetUpload();
  1216. }
  1217. self._validateDefaultPreview();
  1218. },
  1219. _initSortable: function () {
  1220. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS;
  1221. if (!window.KvSortable || $el.find(selector).length === 0) {
  1222. return;
  1223. }
  1224. //noinspection JSUnusedGlobalSymbols
  1225. settings = {
  1226. handle: '.drag-handle-init',
  1227. dataIdAttr: 'data-preview-id',
  1228. scroll: false,
  1229. draggable: selector,
  1230. onSort: function (e) {
  1231. var oldIndex = e.oldIndex, newIndex = e.newIndex, key, $frame;
  1232. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex);
  1233. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1234. self.previewCache.init();
  1235. for (var i = 0; i < self.initialPreviewConfig.length; i++) {
  1236. if (self.initialPreviewConfig[i] !== null) {
  1237. key = self.initialPreviewConfig[i].key;
  1238. $frame = $(".kv-file-remove[data-key='" + key + "']").closest($h.FRAMES);
  1239. $frame.attr('data-fileindex', 'init_' + i).attr('data-fileindex', 'init_' + i);
  1240. }
  1241. }
  1242. self._raise('filesorted', {
  1243. previewId: $(e.item).attr('id'),
  1244. 'oldIndex': oldIndex,
  1245. 'newIndex': newIndex,
  1246. stack: self.initialPreviewConfig
  1247. });
  1248. }
  1249. };
  1250. if ($el.data('kvsortable')) {
  1251. $el.kvsortable('destroy');
  1252. }
  1253. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1254. $el.kvsortable(settings);
  1255. },
  1256. _initPreview: function (isInit) {
  1257. var self = this, cap = self.initialCaption || '', out;
  1258. if (!self.previewCache.count()) {
  1259. self._clearPreview();
  1260. if (isInit) {
  1261. self._setCaption(cap);
  1262. } else {
  1263. self._initCaption();
  1264. }
  1265. return;
  1266. }
  1267. out = self.previewCache.out();
  1268. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1269. self.$preview.html(out.content);
  1270. self._setInitThumbAttr();
  1271. self._setCaption(cap);
  1272. self._initSortable();
  1273. if (!$h.isEmpty(out.content)) {
  1274. self.$container.removeClass('file-input-new');
  1275. }
  1276. },
  1277. _getZoomButton: function (type) {
  1278. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1279. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1280. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1281. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1282. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1283. }
  1284. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1285. },
  1286. _getModalContent: function () {
  1287. var self = this;
  1288. return self._getLayoutTemplate('modal').setTokens({
  1289. 'zoomFrameClass': self.frameClass,
  1290. 'heading': self.msgZoomModalHeading,
  1291. 'prev': self._getZoomButton('prev'),
  1292. 'next': self._getZoomButton('next'),
  1293. 'toggleheader': self._getZoomButton('toggleheader'),
  1294. 'fullscreen': self._getZoomButton('fullscreen'),
  1295. 'borderless': self._getZoomButton('borderless'),
  1296. 'close': self._getZoomButton('close')
  1297. });
  1298. },
  1299. _listenModalEvent: function (event) {
  1300. var self = this, $modal = self.$modal, getParams = function (e) {
  1301. return {
  1302. sourceEvent: e,
  1303. previewId: $modal.data('previewId'),
  1304. modal: $modal
  1305. };
  1306. };
  1307. $modal.on(event + '.bs.modal', function (e) {
  1308. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1309. self._raise('filezoom' + event, getParams(e));
  1310. if (event === 'shown') {
  1311. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1312. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1313. if ($modal.hasClass('file-zoom-fullscreen')) {
  1314. self._maximizeZoomDialog();
  1315. if ($h.checkFullScreen()) {
  1316. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1317. } else {
  1318. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1319. }
  1320. }
  1321. }
  1322. });
  1323. },
  1324. _initZoom: function () {
  1325. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  1326. if (!self.showPreview) {
  1327. return;
  1328. }
  1329. self.$modal = $(modalId);
  1330. if (!self.$modal || !self.$modal.length) {
  1331. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1332. self.$modal = $(modalId).insertBefore($dialog);
  1333. $dialog.remove();
  1334. }
  1335. $h.initModal(self.$modal);
  1336. self.$modal.html(self._getModalContent());
  1337. $.each($h.MODAL_EVENTS, function (key, event) {
  1338. self._listenModalEvent(event);
  1339. });
  1340. },
  1341. _initZoomButtons: function () {
  1342. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last, $preview = self.$preview,
  1343. thumbs = $preview.find($h.FRAMES).toArray(), len = thumbs.length,
  1344. $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next');
  1345. if (thumbs.length < 2) {
  1346. $prev.hide();
  1347. $next.hide();
  1348. return;
  1349. } else {
  1350. $prev.show();
  1351. $next.show();
  1352. }
  1353. if (!len) {
  1354. return;
  1355. }
  1356. $first = $(thumbs[0]);
  1357. $last = $(thumbs[len - 1]);
  1358. $prev.removeAttr('disabled');
  1359. $next.removeAttr('disabled');
  1360. if ($first.length && $first.attr('id') === previewId) {
  1361. $prev.attr('disabled', true);
  1362. }
  1363. if ($last.length && $last.attr('id') === previewId) {
  1364. $next.attr('disabled', true);
  1365. }
  1366. },
  1367. _maximizeZoomDialog: function () {
  1368. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1369. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1370. h = $(window).height(), diff = 0;
  1371. $modal.addClass('file-zoom-fullscreen');
  1372. if ($head && $head.length) {
  1373. h -= $head.outerHeight(true);
  1374. }
  1375. if ($foot && $foot.length) {
  1376. h -= $foot.outerHeight(true);
  1377. }
  1378. if ($body && $body.length) {
  1379. diff = $body.outerHeight(true) - $body.height();
  1380. h -= diff;
  1381. }
  1382. $modal.find('.kv-zoom-body').height(h);
  1383. },
  1384. _resizeZoomDialog: function (fullScreen) {
  1385. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1386. $btnBord = $modal.find('.btn-borderless');
  1387. if ($modal.hasClass('file-zoom-fullscreen')) {
  1388. $h.toggleFullScreen(false);
  1389. if (!fullScreen) {
  1390. if (!$btnFull.hasClass('active')) {
  1391. $modal.removeClass('file-zoom-fullscreen');
  1392. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1393. } else {
  1394. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1395. }
  1396. } else {
  1397. if (!$btnFull.hasClass('active')) {
  1398. $modal.removeClass('file-zoom-fullscreen');
  1399. self._resizeZoomDialog(true);
  1400. if ($btnBord.hasClass('active')) {
  1401. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1402. }
  1403. }
  1404. }
  1405. } else {
  1406. if (!fullScreen) {
  1407. self._maximizeZoomDialog();
  1408. return;
  1409. }
  1410. $h.toggleFullScreen(true);
  1411. }
  1412. $modal.focus();
  1413. },
  1414. _setZoomContent: function ($frame, animate) {
  1415. var self = this, $content, tmplt, body, title, $body, $dataEl, config, pid = $frame.attr('id'),
  1416. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1417. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
  1418. $btnTogh = $modal.find('.btn-toggleheader'), $zoomPreview = self.$preview.find('#zoom-' + pid);
  1419. tmplt = $zoomPreview.attr('data-template') || 'generic';
  1420. $content = $zoomPreview.find('.kv-file-content');
  1421. body = $content.length ? $content.html() : '';
  1422. cap = $frame.data('caption') || '';
  1423. size = $frame.data('size') || '';
  1424. title = cap + ' ' + size;
  1425. $modal.find('.kv-zoom-title').html(title);
  1426. $body = $modal.find('.kv-zoom-body');
  1427. $modal.removeClass('kv-single-content');
  1428. if (animate) {
  1429. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  1430. $body.html(body).hide();
  1431. $tmp.fadeOut('fast', function () {
  1432. $body.fadeIn('fast', function () {
  1433. $body.removeClass('file-thumb-loading');
  1434. });
  1435. $tmp.remove();
  1436. });
  1437. } else {
  1438. $body.html(body);
  1439. }
  1440. config = self.previewZoomSettings[tmplt];
  1441. if (config) {
  1442. $dataEl = $body.find('.kv-preview-data');
  1443. $h.addCss($dataEl, 'file-zoom-detail');
  1444. $.each(config, function (key, value) {
  1445. $dataEl.css(key, value);
  1446. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1447. $dataEl.removeAttr(key);
  1448. }
  1449. });
  1450. }
  1451. $modal.data('previewId', pid);
  1452. var $img = $body.find('img');
  1453. if ($img.length) {
  1454. $h.adjustOrientedImage($img, true);
  1455. }
  1456. self._handler($prev, 'click', function () {
  1457. self._zoomSlideShow('prev', pid);
  1458. });
  1459. self._handler($next, 'click', function () {
  1460. self._zoomSlideShow('next', pid);
  1461. });
  1462. self._handler($btnFull, 'click', function () {
  1463. self._resizeZoomDialog(true);
  1464. });
  1465. self._handler($btnBord, 'click', function () {
  1466. self._resizeZoomDialog(false);
  1467. });
  1468. self._handler($btnTogh, 'click', function () {
  1469. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1470. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1471. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1472. if ($modal.hasClass('file-zoom-fullscreen')) {
  1473. h = $body.outerHeight(true);
  1474. if (!height) {
  1475. h = h - $header.outerHeight(true);
  1476. }
  1477. }
  1478. $body.css('height', height ? h + height : h);
  1479. };
  1480. if ($header.is(':visible')) {
  1481. ht = $header.outerHeight(true);
  1482. $header.slideUp('slow', function () {
  1483. $actions.find('.btn').appendTo($floatBar);
  1484. resize(ht);
  1485. });
  1486. } else {
  1487. $floatBar.find('.btn').appendTo($actions);
  1488. $header.slideDown('slow', function () {
  1489. resize();
  1490. });
  1491. }
  1492. $modal.focus();
  1493. });
  1494. self._handler($modal, 'keydown', function (e) {
  1495. var key = e.which || e.keyCode;
  1496. if (key === 37 && !$prev.attr('disabled')) {
  1497. self._zoomSlideShow('prev', pid);
  1498. }
  1499. if (key === 39 && !$next.attr('disabled')) {
  1500. self._zoomSlideShow('next', pid);
  1501. }
  1502. });
  1503. },
  1504. _zoomPreview: function ($btn) {
  1505. var self = this, $frame, $modal = self.$modal;
  1506. if (!$btn.length) {
  1507. throw 'Cannot zoom to detailed preview!';
  1508. }
  1509. $h.initModal($modal);
  1510. $modal.html(self._getModalContent());
  1511. $frame = $btn.closest($h.FRAMES);
  1512. self._setZoomContent($frame);
  1513. $modal.modal('show');
  1514. self._initZoomButtons();
  1515. },
  1516. _zoomSlideShow: function (dir, previewId) {
  1517. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1518. thumbs = self.$preview.find($h.FRAMES).toArray(), len = thumbs.length, out;
  1519. if ($btn.attr('disabled')) {
  1520. return;
  1521. }
  1522. for (i = 0; i < len; i++) {
  1523. if ($(thumbs[i]).attr('id') === previewId) {
  1524. out = dir === 'prev' ? i - 1 : i + 1;
  1525. break;
  1526. }
  1527. }
  1528. if (out < 0 || out >= len || !thumbs[out]) {
  1529. return;
  1530. }
  1531. $targFrame = $(thumbs[out]);
  1532. if ($targFrame.length) {
  1533. self._setZoomContent($targFrame, true);
  1534. }
  1535. self._initZoomButtons();
  1536. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1537. },
  1538. _initZoomButton: function () {
  1539. var self = this;
  1540. self.$preview.find('.kv-file-zoom').each(function () {
  1541. var $el = $(this);
  1542. self._handler($el, 'click', function () {
  1543. self._zoomPreview($el);
  1544. });
  1545. });
  1546. },
  1547. _clearObjects: function ($el) {
  1548. $el.find('video audio').each(function () {
  1549. this.pause();
  1550. $(this).remove();
  1551. });
  1552. $el.find('img object div').each(function () {
  1553. $(this).remove();
  1554. });
  1555. },
  1556. _clearFileInput: function () {
  1557. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1558. self.fileInputCleared = true;
  1559. if ($h.isEmpty($el.val())) {
  1560. return;
  1561. }
  1562. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1563. // crashing but still allow clearing of the file input.
  1564. if (self.isIE9 || self.isIE10) {
  1565. $srcFrm = $el.closest('form');
  1566. $tmpFrm = $(document.createElement('form'));
  1567. $tmpEl = $(document.createElement('div'));
  1568. $el.before($tmpEl);
  1569. if ($srcFrm.length) {
  1570. $srcFrm.after($tmpFrm);
  1571. } else {
  1572. $tmpEl.after($tmpFrm);
  1573. }
  1574. $tmpFrm.append($el).trigger('reset');
  1575. $tmpEl.before($el).remove();
  1576. $tmpFrm.remove();
  1577. } else { // normal input clear behavior for other sane browsers
  1578. $el.val('');
  1579. }
  1580. },
  1581. _resetUpload: function () {
  1582. var self = this;
  1583. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1584. self.uploadCount = 0;
  1585. self.uploadStatus = {};
  1586. self.uploadLog = [];
  1587. self.uploadAsyncCount = 0;
  1588. self.loadedImages = [];
  1589. self.totalImagesCount = 0;
  1590. self.$btnUpload.removeAttr('disabled');
  1591. self._setProgress(0);
  1592. $h.addCss(self.$progress, 'hide');
  1593. self._resetErrors(false);
  1594. self.ajaxAborted = false;
  1595. self.ajaxRequests = [];
  1596. self._resetCanvas();
  1597. self.cacheInitialPreview = {};
  1598. if (self.overwriteInitial) {
  1599. self.initialPreview = [];
  1600. self.initialPreviewConfig = [];
  1601. self.initialPreviewThumbTags = [];
  1602. self.previewCache.data = {
  1603. content: [],
  1604. config: [],
  1605. tags: []
  1606. };
  1607. }
  1608. },
  1609. _resetCanvas: function () {
  1610. var self = this;
  1611. if (self.canvas && self.imageCanvasContext) {
  1612. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1613. }
  1614. },
  1615. _hasInitialPreview: function () {
  1616. var self = this;
  1617. return !self.overwriteInitial && self.previewCache.count();
  1618. },
  1619. _resetPreview: function () {
  1620. var self = this, out, cap;
  1621. if (self.previewCache.count()) {
  1622. out = self.previewCache.out();
  1623. self.$preview.html(out.content);
  1624. self._setInitThumbAttr();
  1625. cap = self.initialCaption ? self.initialCaption : out.caption;
  1626. self._setCaption(cap);
  1627. } else {
  1628. self._clearPreview();
  1629. self._initCaption();
  1630. }
  1631. if (self.showPreview) {
  1632. self._initZoom();
  1633. self._initSortable();
  1634. }
  1635. },
  1636. _clearDefaultPreview: function () {
  1637. var self = this;
  1638. self.$preview.find('.file-default-preview').remove();
  1639. },
  1640. _validateDefaultPreview: function () {
  1641. var self = this;
  1642. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  1643. return;
  1644. }
  1645. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1646. self.$container.removeClass('file-input-new');
  1647. self._initClickable();
  1648. },
  1649. _resetPreviewThumbs: function (isAjax) {
  1650. var self = this, out;
  1651. if (isAjax) {
  1652. self._clearPreview();
  1653. self.clearStack();
  1654. return;
  1655. }
  1656. if (self._hasInitialPreview()) {
  1657. out = self.previewCache.out();
  1658. self.$preview.html(out.content);
  1659. self._setInitThumbAttr();
  1660. self._setCaption(out.caption);
  1661. self._initPreviewActions();
  1662. } else {
  1663. self._clearPreview();
  1664. }
  1665. },
  1666. _getLayoutTemplate: function (t) {
  1667. var self = this, template = self.layoutTemplates[t];
  1668. if ($h.isEmpty(self.customLayoutTags)) {
  1669. return template;
  1670. }
  1671. return $h.replaceTags(template, self.customLayoutTags);
  1672. },
  1673. _getPreviewTemplate: function (t) {
  1674. var self = this, template = self.previewTemplates[t];
  1675. if ($h.isEmpty(self.customPreviewTags)) {
  1676. return template;
  1677. }
  1678. return $h.replaceTags(template, self.customPreviewTags);
  1679. },
  1680. _getOutData: function (jqXHR, responseData, filesData) {
  1681. var self = this;
  1682. jqXHR = jqXHR || {};
  1683. responseData = responseData || {};
  1684. filesData = filesData || self.filestack.slice(0) || {};
  1685. return {
  1686. form: self.formdata,
  1687. files: filesData,
  1688. filenames: self.filenames,
  1689. filescount: self.getFilesCount(),
  1690. extra: self._getExtraData(),
  1691. response: responseData,
  1692. reader: self.reader,
  1693. jqXHR: jqXHR
  1694. };
  1695. },
  1696. _getMsgSelected: function (n) {
  1697. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1698. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1699. },
  1700. _getThumbs: function (css) {
  1701. css = css || '';
  1702. return this.$preview.find($h.FRAMES + ':not(.file-preview-initial)' + css);
  1703. },
  1704. _getExtraData: function (previewId, index) {
  1705. var self = this, data = self.uploadExtraData;
  1706. if (typeof self.uploadExtraData === "function") {
  1707. data = self.uploadExtraData(previewId, index);
  1708. }
  1709. return data;
  1710. },
  1711. _initXhr: function (xhrobj, previewId, fileCount) {
  1712. var self = this;
  1713. if (xhrobj.upload) {
  1714. xhrobj.upload.addEventListener('progress', function (event) {
  1715. var pct = 0, total = event.total, position = event.loaded || event.position;
  1716. /** @namespace event.lengthComputable */
  1717. if (event.lengthComputable) {
  1718. pct = Math.floor(position / total * 100);
  1719. }
  1720. if (previewId) {
  1721. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1722. } else {
  1723. self._setProgress(pct);
  1724. }
  1725. }, false);
  1726. }
  1727. return xhrobj;
  1728. },
  1729. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1730. var self = this, settings;
  1731. if (!self._raise('filepreajax', [previewId, index])) {
  1732. return;
  1733. }
  1734. self._uploadExtra(previewId, index);
  1735. settings = $.extend(true, {}, {
  1736. xhr: function () {
  1737. var xhrobj = $.ajaxSettings.xhr();
  1738. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1739. },
  1740. url: self.uploadUrl,
  1741. type: 'POST',
  1742. dataType: 'json',
  1743. data: self.formdata,
  1744. cache: false,
  1745. processData: false,
  1746. contentType: false,
  1747. beforeSend: fnBefore,
  1748. success: fnSuccess,
  1749. complete: fnComplete,
  1750. error: fnError
  1751. }, self.ajaxSettings);
  1752. self.ajaxRequests.push($.ajax(settings));
  1753. },
  1754. _mergeArray: function (prop, content) {
  1755. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  1756. self[prop] = arr1.concat(arr2);
  1757. },
  1758. _initUploadSuccess: function (out, $thumb, allFiles) {
  1759. var self = this, append, data, index, $div, $newCache, content, config, tags, i;
  1760. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1761. return;
  1762. }
  1763. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1764. self.hasInitData = true;
  1765. content = out.initialPreview || [];
  1766. config = out.initialPreviewConfig || [];
  1767. tags = out.initialPreviewThumbTags || [];
  1768. append = out.append === undefined || out.append ? true : false;
  1769. if (content.length > 0 && !$h.isArray(content)) {
  1770. content = content.split(self.initialPreviewDelimiter);
  1771. }
  1772. self._mergeArray('initialPreview', content);
  1773. self._mergeArray('initialPreviewConfig', config);
  1774. self._mergeArray('initialPreviewThumbTags', tags);
  1775. if ($thumb !== undefined) {
  1776. if (!allFiles) {
  1777. index = self.previewCache.add(content, config[0], tags[0], append);
  1778. data = self.previewCache.get(index, false);
  1779. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  1780. $newCache = $div.find('.kv-zoom-cache');
  1781. if ($newCache && $newCache.length) {
  1782. $newCache.insertAfter($thumb);
  1783. }
  1784. $thumb.fadeOut('slow', function () {
  1785. var $newThumb = $div.find('.file-preview-frame');
  1786. if ($newThumb && $newThumb.length) {
  1787. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  1788. }
  1789. self._initPreviewActions();
  1790. self._clearFileInput();
  1791. $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
  1792. $thumb.remove();
  1793. $div.remove();
  1794. self._initSortable();
  1795. });
  1796. } else {
  1797. i = $thumb.attr('data-fileindex');
  1798. self.uploadCache.content[i] = content[0];
  1799. self.uploadCache.config[i] = config[0] || [];
  1800. self.uploadCache.tags[i] = tags[0] || [];
  1801. self.uploadCache.append = append;
  1802. }
  1803. } else {
  1804. self.previewCache.set(content, config, tags, append);
  1805. self._initPreview();
  1806. self._initPreviewActions();
  1807. }
  1808. }
  1809. },
  1810. _initSuccessThumbs: function () {
  1811. var self = this;
  1812. if (!self.showPreview) {
  1813. return;
  1814. }
  1815. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  1816. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  1817. $remove.removeAttr('disabled');
  1818. self._handler($remove, 'click', function () {
  1819. var id = $thumb.attr('id'),
  1820. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  1821. $h.cleanMemory($thumb);
  1822. if (out === false) {
  1823. return;
  1824. }
  1825. $thumb.fadeOut('slow', function () {
  1826. $h.cleanZoomCache($preview.find('#zoom-' + id));
  1827. $thumb.remove();
  1828. if (!$preview.find($h.FRAMES).length) {
  1829. self.reset();
  1830. }
  1831. });
  1832. });
  1833. });
  1834. },
  1835. _checkAsyncComplete: function () {
  1836. var self = this, previewId, i;
  1837. for (i = 0; i < self.filestack.length; i++) {
  1838. if (self.filestack[i]) {
  1839. previewId = self.previewInitId + "-" + i;
  1840. if ($.inArray(previewId, self.uploadLog) === -1) {
  1841. return false;
  1842. }
  1843. }
  1844. }
  1845. return (self.uploadAsyncCount === self.uploadLog.length);
  1846. },
  1847. _uploadExtra: function (previewId, index) {
  1848. var self = this, data = self._getExtraData(previewId, index);
  1849. if (data.length === 0) {
  1850. return;
  1851. }
  1852. $.each(data, function (key, value) {
  1853. self.formdata.append(key, value);
  1854. });
  1855. },
  1856. _uploadSingle: function (i, files, allFiles) {
  1857. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1858. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1859. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1860. $prog = $('#' + previewId).find('.file-thumb-progress'),
  1861. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1862. self.formdata = formdata;
  1863. if (self.showPreview) {
  1864. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1865. $btnUpload = $thumb.find('.kv-file-upload');
  1866. $btnDelete = $thumb.find('.kv-file-remove');
  1867. $prog.removeClass('hide');
  1868. }
  1869. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1870. return;
  1871. }
  1872. updateUploadLog = function (i, previewId) {
  1873. self.updateStack(i, undefined);
  1874. self.uploadLog.push(previewId);
  1875. if (self._checkAsyncComplete()) {
  1876. self.fileBatchCompleted = true;
  1877. }
  1878. };
  1879. chkComplete = function () {
  1880. var u = self.uploadCache, $initThumbs, i, j, len = 0, data = self.cacheInitialPreview;
  1881. if (!self.fileBatchCompleted) {
  1882. return;
  1883. }
  1884. if (data && data.content) {
  1885. len = data.content.length;
  1886. }
  1887. setTimeout(function () {
  1888. if (self.showPreview) {
  1889. self.previewCache.set(u.content, u.config, u.tags, u.append);
  1890. if (len) {
  1891. for (i = 0; i < u.content.length; i++) {
  1892. j = i + len;
  1893. data.content[j] = u.content[i];
  1894. if (data.config.length) {
  1895. data.config[j] = u.config[i];
  1896. }
  1897. if (data.tags.length) {
  1898. data.tags[j] = u.tags[i];
  1899. }
  1900. }
  1901. self.initialPreview = $h.cleanArray(data.content);
  1902. self.initialPreviewConfig = $h.cleanArray(data.config);
  1903. self.initialPreviewThumbTags = $h.cleanArray(data.tags);
  1904. } else {
  1905. self.initialPreview = u.content;
  1906. self.initialPreviewConfig = u.config;
  1907. self.initialPreviewThumbTags = u.tags;
  1908. }
  1909. self.cacheInitialPreview = {};
  1910. if (self.hasInitData) {
  1911. self._initPreview();
  1912. self._initPreviewActions();
  1913. }
  1914. }
  1915. self.unlock();
  1916. self._clearFileInput();
  1917. $initThumbs = self.$preview.find('.file-preview-initial');
  1918. if (self.uploadAsync && $initThumbs.length) {
  1919. $h.addCss($initThumbs, $h.SORT_CSS);
  1920. self._initSortable();
  1921. }
  1922. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1923. self.uploadCount = 0;
  1924. self.uploadStatus = {};
  1925. self.uploadLog = [];
  1926. self._setProgress(101);
  1927. }, 100);
  1928. };
  1929. fnBefore = function (jqXHR) {
  1930. outData = self._getOutData(jqXHR);
  1931. self.fileBatchCompleted = false;
  1932. if (self.showPreview) {
  1933. if (!$thumb.hasClass('file-preview-success')) {
  1934. self._setThumbStatus($thumb, 'Loading');
  1935. $h.addCss($thumb, 'file-uploading');
  1936. }
  1937. $btnUpload.attr('disabled', true);
  1938. $btnDelete.attr('disabled', true);
  1939. }
  1940. if (!allFiles) {
  1941. self.lock();
  1942. }
  1943. self._raise('filepreupload', [outData, previewId, i]);
  1944. $.extend(true, params, outData);
  1945. if (self._abort(params)) {
  1946. jqXHR.abort();
  1947. self._setProgressCancelled();
  1948. }
  1949. };
  1950. fnSuccess = function (data, textStatus, jqXHR) {
  1951. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  1952. outData = self._getOutData(jqXHR, data);
  1953. $.extend(true, params, outData);
  1954. setTimeout(function () {
  1955. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  1956. if (self.showPreview) {
  1957. self._setThumbStatus($thumb, 'Success');
  1958. $btnUpload.hide();
  1959. self._initUploadSuccess(data, $thumb, allFiles);
  1960. self._setProgress(101, $prog);
  1961. }
  1962. self._raise('fileuploaded', [outData, pid, i]);
  1963. if (!allFiles) {
  1964. self.updateStack(i, undefined);
  1965. } else {
  1966. updateUploadLog(i, pid);
  1967. }
  1968. } else {
  1969. self._showUploadError(data.error, params);
  1970. self._setPreviewError($thumb, i);
  1971. if (allFiles) {
  1972. updateUploadLog(i, pid);
  1973. }
  1974. }
  1975. }, 100);
  1976. };
  1977. fnComplete = function () {
  1978. setTimeout(function () {
  1979. if (self.showPreview) {
  1980. $btnUpload.removeAttr('disabled');
  1981. $btnDelete.removeAttr('disabled');
  1982. $thumb.removeClass('file-uploading');
  1983. }
  1984. if (!allFiles) {
  1985. self.unlock(false);
  1986. self._clearFileInput();
  1987. } else {
  1988. chkComplete();
  1989. }
  1990. self._initSuccessThumbs();
  1991. }, 100);
  1992. };
  1993. fnError = function (jqXHR, textStatus, errorThrown) {
  1994. var op = self.ajaxOperations.uploadThumb,
  1995. errMsg = self._parseError(op, jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1996. setTimeout(function () {
  1997. if (allFiles) {
  1998. updateUploadLog(i, previewId);
  1999. }
  2000. self.uploadStatus[previewId] = 100;
  2001. self._setPreviewError($thumb, i);
  2002. $.extend(true, params, self._getOutData(jqXHR));
  2003. self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
  2004. self._showUploadError(errMsg, params);
  2005. }, 100);
  2006. };
  2007. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  2008. formdata.append('file_id', i);
  2009. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  2010. },
  2011. _uploadBatch: function () {
  2012. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  2013. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  2014. setAllUploaded;
  2015. self.formdata = new FormData();
  2016. if (total === 0 || !hasPostData || self._abort(params)) {
  2017. return;
  2018. }
  2019. setAllUploaded = function () {
  2020. $.each(files, function (key) {
  2021. self.updateStack(key, undefined);
  2022. });
  2023. self._clearFileInput();
  2024. };
  2025. fnBefore = function (jqXHR) {
  2026. self.lock();
  2027. var outData = self._getOutData(jqXHR);
  2028. if (self.showPreview) {
  2029. self._getThumbs().each(function () {
  2030. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  2031. $btnDelete = $thumb.find('.kv-file-remove');
  2032. if (!$thumb.hasClass('file-preview-success')) {
  2033. self._setThumbStatus($thumb, 'Loading');
  2034. $h.addCss($thumb, 'file-uploading');
  2035. }
  2036. $btnUpload.attr('disabled', true);
  2037. $btnDelete.attr('disabled', true);
  2038. });
  2039. }
  2040. self._raise('filebatchpreupload', [outData]);
  2041. if (self._abort(outData)) {
  2042. jqXHR.abort();
  2043. self._setProgressCancelled();
  2044. }
  2045. };
  2046. fnSuccess = function (data, textStatus, jqXHR) {
  2047. /** @namespace data.errorkeys */
  2048. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(':not(.file-preview-error)'),
  2049. key = 0,
  2050. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  2051. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2052. self._raise('filebatchuploadsuccess', [outData]);
  2053. setAllUploaded();
  2054. if (self.showPreview) {
  2055. $thumbs.each(function () {
  2056. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  2057. $thumb.find('.kv-file-upload').hide();
  2058. self._setThumbStatus($thumb, 'Success');
  2059. $thumb.removeClass('file-uploading');
  2060. $btnUpload.removeAttr('disabled');
  2061. });
  2062. self._initUploadSuccess(data);
  2063. } else {
  2064. self.reset();
  2065. }
  2066. self._setProgress(101);
  2067. } else {
  2068. if (self.showPreview) {
  2069. $thumbs.each(function () {
  2070. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  2071. $btnUpload = $thumb.find('.kv-file-upload');
  2072. $thumb.removeClass('file-uploading');
  2073. $btnUpload.removeAttr('disabled');
  2074. $btnDelete.removeAttr('disabled');
  2075. if (keys.length === 0) {
  2076. self._setPreviewError($thumb);
  2077. return;
  2078. }
  2079. if ($.inArray(key, keys) !== -1) {
  2080. self._setPreviewError($thumb);
  2081. } else {
  2082. $thumb.find('.kv-file-upload').hide();
  2083. self._setThumbStatus($thumb, 'Success');
  2084. self.updateStack(key, undefined);
  2085. }
  2086. key++;
  2087. });
  2088. self._initUploadSuccess(data);
  2089. }
  2090. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2091. }
  2092. };
  2093. fnComplete = function () {
  2094. self.unlock();
  2095. self._initSuccessThumbs();
  2096. self._clearFileInput();
  2097. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2098. };
  2099. fnError = function (jqXHR, textStatus, errorThrown) {
  2100. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch,
  2101. errMsg = self._parseError(op, jqXHR, errorThrown);
  2102. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2103. self.uploadFileCount = total - 1;
  2104. if (!self.showPreview) {
  2105. return;
  2106. }
  2107. self._getThumbs().each(function () {
  2108. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  2109. $thumb.removeClass('file-uploading');
  2110. if (self.filestack[key] !== undefined) {
  2111. self._setPreviewError($thumb);
  2112. }
  2113. });
  2114. self._getThumbs().removeClass('file-uploading');
  2115. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2116. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2117. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2118. };
  2119. $.each(files, function (key, data) {
  2120. if (!$h.isEmpty(files[key])) {
  2121. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2122. }
  2123. });
  2124. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2125. },
  2126. _uploadExtraOnly: function () {
  2127. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2128. self.formdata = new FormData();
  2129. if (self._abort(params)) {
  2130. return;
  2131. }
  2132. fnBefore = function (jqXHR) {
  2133. self.lock();
  2134. var outData = self._getOutData(jqXHR);
  2135. self._raise('filebatchpreupload', [outData]);
  2136. self._setProgress(50);
  2137. params.data = outData;
  2138. params.xhr = jqXHR;
  2139. if (self._abort(params)) {
  2140. jqXHR.abort();
  2141. self._setProgressCancelled();
  2142. }
  2143. };
  2144. fnSuccess = function (data, textStatus, jqXHR) {
  2145. var outData = self._getOutData(jqXHR, data);
  2146. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2147. self._raise('filebatchuploadsuccess', [outData]);
  2148. self._clearFileInput();
  2149. self._initUploadSuccess(data);
  2150. self._setProgress(101);
  2151. } else {
  2152. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2153. }
  2154. };
  2155. fnComplete = function () {
  2156. self.unlock();
  2157. self._clearFileInput();
  2158. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2159. };
  2160. fnError = function (jqXHR, textStatus, errorThrown) {
  2161. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra,
  2162. errMsg = self._parseError(op, jqXHR, errorThrown);
  2163. params.data = outData;
  2164. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2165. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2166. };
  2167. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2168. },
  2169. _deleteFileIndex: function ($frame) {
  2170. var self = this, ind = $frame.attr('data-fileindex');
  2171. if (ind.substring(0, 5) === 'init_') {
  2172. ind = parseInt(ind.replace('init_', ''));
  2173. self.initialPreview = $h.spliceArray(self.initialPreview, ind);
  2174. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind);
  2175. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind);
  2176. self.$preview.find($h.FRAMES).each(function () {
  2177. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  2178. if (nInd.substring(0, 5) === 'init_') {
  2179. nInd = parseInt(nInd.replace('init_', ''));
  2180. if (nInd > ind) {
  2181. nInd--;
  2182. $nFrame.attr('data-fileindex', 'init_' + nInd);
  2183. }
  2184. }
  2185. });
  2186. if (self.uploadAsync) {
  2187. self.cacheInitialPreview = self.getPreview();
  2188. }
  2189. }
  2190. },
  2191. _initFileActions: function () {
  2192. var self = this, $preview = self.$preview;
  2193. if (!self.showPreview) {
  2194. return;
  2195. }
  2196. self._initZoomButton();
  2197. $preview.find($h.FRAMES + ' .kv-file-remove').each(function () {
  2198. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  2199. ind = $frame.attr('data-fileindex'), n, cap, status;
  2200. self._handler($el, 'click', function () {
  2201. status = self._raise('filepreremove', [id, ind]);
  2202. if (status === false || !self._validateMinCount()) {
  2203. return false;
  2204. }
  2205. hasError = $frame.hasClass('file-preview-error');
  2206. $h.cleanMemory($frame);
  2207. $frame.fadeOut('slow', function () {
  2208. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2209. self.updateStack(ind, undefined);
  2210. self._clearObjects($frame);
  2211. $frame.remove();
  2212. if (id && hasError) {
  2213. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2214. $(this).remove();
  2215. if (!self._errorsExist()) {
  2216. self._resetErrors();
  2217. }
  2218. });
  2219. }
  2220. self._clearFileInput();
  2221. var filestack = self.getFileStack(true), chk = self.previewCache.count(),
  2222. len = filestack.length,
  2223. hasThumb = self.showPreview && $preview.find($h.FRAMES).length;
  2224. if (len === 0 && chk === 0 && !hasThumb) {
  2225. self.reset();
  2226. } else {
  2227. n = chk + len;
  2228. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2229. self._setCaption(cap);
  2230. }
  2231. self._raise('fileremoved', [id, ind]);
  2232. });
  2233. });
  2234. });
  2235. self.$preview.find($h.FRAMES + ' .kv-file-upload').each(function () {
  2236. var $el = $(this);
  2237. self._handler($el, 'click', function () {
  2238. var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex');
  2239. if (!$frame.hasClass('file-preview-error')) {
  2240. self._uploadSingle(ind, self.filestack, false);
  2241. }
  2242. });
  2243. });
  2244. },
  2245. _initPreviewActions: function () {
  2246. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  2247. btnRemove = $h.FRAMES + ' .kv-file-remove',
  2248. resetProgress = function () {
  2249. var hasFiles = self.isUploadable ? self.previewCache.count() : self.$element.get(0).files.length;
  2250. if ($preview.find(btnRemove).length === 0 && !hasFiles) {
  2251. self.reset();
  2252. self.initialCaption = '';
  2253. }
  2254. };
  2255. self._initZoomButton();
  2256. $preview.find(btnRemove).each(function () {
  2257. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  2258. if ($h.isEmpty(vUrl) || vKey === undefined) {
  2259. return;
  2260. }
  2261. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data,
  2262. settings, params, index = $frame.attr('data-fileindex'), config, extraData;
  2263. index = parseInt(index.replace('init_', ''));
  2264. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  2265. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  2266. if (typeof extraData === "function") {
  2267. extraData = extraData();
  2268. }
  2269. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  2270. settings = $.extend(true, {}, {
  2271. url: vUrl,
  2272. type: 'POST',
  2273. dataType: 'json',
  2274. data: $.extend(true, {}, {key: vKey}, extraData),
  2275. beforeSend: function (jqXHR) {
  2276. self.ajaxAborted = false;
  2277. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  2278. if (self.ajaxAborted) {
  2279. jqXHR.abort();
  2280. } else {
  2281. $h.addCss($frame, 'file-uploading');
  2282. $h.addCss($el, 'disabled');
  2283. }
  2284. },
  2285. success: function (data, textStatus, jqXHR) {
  2286. var n, cap;
  2287. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2288. index = parseInt(($frame.attr('data-fileindex')).replace('init_', ''));
  2289. self.previewCache.unset(index);
  2290. n = self.previewCache.count();
  2291. cap = n > 0 ? self._getMsgSelected(n) : '';
  2292. self._deleteFileIndex($frame);
  2293. self._setCaption(cap);
  2294. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  2295. } else {
  2296. params.jqXHR = jqXHR;
  2297. params.response = data;
  2298. self._showError(data.error, params, 'filedeleteerror');
  2299. $frame.removeClass('file-uploading');
  2300. $el.removeClass('disabled');
  2301. resetProgress();
  2302. return;
  2303. }
  2304. $frame.removeClass('file-uploading').addClass('file-deleted');
  2305. $frame.fadeOut('slow', function () {
  2306. $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
  2307. self._clearObjects($frame);
  2308. $frame.remove();
  2309. resetProgress();
  2310. if (!n && self.getFileStack().length === 0) {
  2311. self._setCaption('');
  2312. self.reset();
  2313. }
  2314. });
  2315. },
  2316. error: function (jqXHR, textStatus, errorThrown) {
  2317. var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown);
  2318. params.jqXHR = jqXHR;
  2319. params.response = {};
  2320. self._showError(errMsg, params, 'filedeleteerror');
  2321. $frame.removeClass('file-uploading');
  2322. resetProgress();
  2323. }
  2324. }, self.ajaxDeleteSettings);
  2325. self._handler($el, 'click', function () {
  2326. if (!self._validateMinCount()) {
  2327. return false;
  2328. }
  2329. $.ajax(settings);
  2330. });
  2331. });
  2332. },
  2333. _hideFileIcon: function () {
  2334. if (this.overwriteInitial) {
  2335. this.$captionContainer.find('.kv-caption-icon').hide();
  2336. }
  2337. },
  2338. _showFileIcon: function () {
  2339. this.$captionContainer.find('.kv-caption-icon').show();
  2340. },
  2341. _getSize: function (bytes) {
  2342. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out;
  2343. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  2344. return '';
  2345. }
  2346. if (typeof func === 'function') {
  2347. out = func(size);
  2348. } else {
  2349. if (size === 0) {
  2350. out = '0.00 B';
  2351. } else {
  2352. i = Math.floor(Math.log(size) / Math.log(1024));
  2353. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2354. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2355. }
  2356. }
  2357. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2358. },
  2359. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) {
  2360. var self = this, caption = self.slug(fname), prevContent, zoomContent = '',
  2361. config = self.previewSettings[cat] || self.defaults.previewSettings[cat],
  2362. w = config && config.width ? config.width : '', h = config && config.height ? config.height : '',
  2363. footer = foot || self._renderFileFooter(caption, size, ($h.isEmpty(w) ? 'auto' : w), isError),
  2364. hasIconSetting = self._getPreviewIcon(fname), typeCss = 'type-default',
  2365. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2366. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview,
  2367. getContent = function (c, d, zoom, frameCss) {
  2368. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2369. css = (frameClass || '') + ' ' + frameCss;
  2370. if (self.frameClass) {
  2371. css = self.frameClass + ' ' + css;
  2372. }
  2373. if (zoom) {
  2374. css = css.replace(' ' + $h.SORT_CSS, '');
  2375. }
  2376. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2377. if (c === 'text') {
  2378. d = $h.htmlEncode(d);
  2379. }
  2380. if (cat === 'object' && !ftype) {
  2381. $.each(self.defaults.fileTypeSettings, function (key, func) {
  2382. if (key === 'object' || key === 'other') {
  2383. return;
  2384. }
  2385. if (func(fname, ftype)) {
  2386. typeCss = 'type-' + key;
  2387. }
  2388. });
  2389. }
  2390. return tmplt.setTokens({
  2391. 'previewId': id,
  2392. 'caption': caption,
  2393. 'frameClass': css,
  2394. 'type': ftype,
  2395. 'fileindex': ind,
  2396. 'width': w,
  2397. 'height': h,
  2398. 'typeCss': typeCss,
  2399. 'footer': footer,
  2400. 'data': d,
  2401. 'template': templ || cat
  2402. });
  2403. };
  2404. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2405. if (self.fileActionSettings.showZoom) {
  2406. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2407. }
  2408. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  2409. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2410. return prevContent + zoomContent;
  2411. },
  2412. _previewDefault: function (file, previewId, isDisabled) {
  2413. var self = this, $preview = self.$preview;
  2414. if (!self.showPreview) {
  2415. return;
  2416. }
  2417. var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size || 0,
  2418. caption = self.slug(fname), isError = isDisabled === true && !self.isUploadable,
  2419. data = $h.objUrl.createObjectURL(file);
  2420. self._clearDefaultPreview();
  2421. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size);
  2422. $preview.append("\n" + content);
  2423. self._setThumbAttr(previewId, caption, size);
  2424. if (isDisabled === true && self.isUploadable) {
  2425. self._setThumbStatus($('#' + previewId), 'Error');
  2426. }
  2427. },
  2428. _previewFile: function (i, file, theFile, previewId, data) {
  2429. if (!this.showPreview) {
  2430. return;
  2431. }
  2432. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  2433. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview,
  2434. chkTypes = types && types.indexOf(cat) >= 0, fsize = file.size || 0, ftype = file.type,
  2435. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content,
  2436. chkMimes = mimes && mimes.indexOf(ftype) !== -1;
  2437. /** @namespace window.DOMPurify */
  2438. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2439. iData = window.DOMPurify.sanitize(iData);
  2440. }
  2441. if (chkTypes || chkMimes) {
  2442. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, false, fsize);
  2443. self._clearDefaultPreview();
  2444. $preview.append("\n" + content);
  2445. var $img = $preview.find('#' + previewId + ' img');
  2446. if ($img.length && self.autoOrientImage) {
  2447. $h.validateOrientation(file, function (value) {
  2448. if (value) {
  2449. var $zoomImg = $preview.find('#zoom-' + previewId + ' img'), css = 'rotate-' + value;
  2450. if (value > 4) {
  2451. css += ($img.width() > $img.height() ? ' is-portrait-gt4' : ' is-landscape-gt4');
  2452. }
  2453. $h.addCss($img, css);
  2454. $h.addCss($zoomImg, css);
  2455. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  2456. }
  2457. self._validateImage(previewId, caption, ftype, fsize);
  2458. $h.adjustOrientedImage($img);
  2459. });
  2460. } else {
  2461. self._validateImage(previewId, caption, ftype, fsize);
  2462. }
  2463. } else {
  2464. self._previewDefault(file, previewId);
  2465. }
  2466. self._setThumbAttr(previewId, caption, fsize);
  2467. self._initSortable();
  2468. },
  2469. _setThumbAttr: function (id, caption, size) {
  2470. var self = this, $frame = $('#' + id);
  2471. if ($frame.length) {
  2472. size = size && size > 0 ? self._getSize(size) : '';
  2473. $frame.data({'caption': caption, 'size': size});
  2474. }
  2475. },
  2476. _setInitThumbAttr: function () {
  2477. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  2478. caption, size, previewId;
  2479. if (len === 0) {
  2480. return;
  2481. }
  2482. for (var i = 0; i < len; i++) {
  2483. config = data.config[i];
  2484. previewId = self.previewInitId + '-' + 'init_' + i;
  2485. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  2486. size = $h.ifSet('size', config);
  2487. self._setThumbAttr(previewId, caption, size);
  2488. }
  2489. },
  2490. _slugDefault: function (text) {
  2491. return $h.isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2492. },
  2493. _readFiles: function (files) {
  2494. this.reader = new FileReader();
  2495. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2496. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2497. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2498. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2499. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  2500. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  2501. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2502. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2503. throwError = function (msg, file, previewId, index) {
  2504. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2505. p2 = {id: previewId, index: index, file: file, files: files};
  2506. self._previewDefault(file, previewId, true);
  2507. if (self.isUploadable) {
  2508. self.addToStack(undefined);
  2509. setTimeout(function () {
  2510. readFile(index + 1);
  2511. }, 100);
  2512. }
  2513. self._initFileActions();
  2514. if (self.removeFromPreviewOnError) {
  2515. $('#' + previewId).remove();
  2516. }
  2517. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2518. };
  2519. self.loadedImages = [];
  2520. self.totalImagesCount = 0;
  2521. $.each(files, function (key, file) {
  2522. var func = self.fileTypeSettings.image;
  2523. if (func && func(file.type)) {
  2524. self.totalImagesCount++;
  2525. }
  2526. });
  2527. readFile = function (i) {
  2528. if ($h.isEmpty($el.attr('multiple'))) {
  2529. numFiles = 1;
  2530. }
  2531. if (i >= numFiles) {
  2532. if (self.isUploadable && self.filestack.length > 0) {
  2533. self._raise('filebatchselected', [self.getFileStack()]);
  2534. } else {
  2535. self._raise('filebatchselected', [files]);
  2536. }
  2537. $container.removeClass('file-thumb-loading');
  2538. $status.html('');
  2539. return;
  2540. }
  2541. var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i], fSizeKB,
  2542. caption = file.name ? self.slug(file.name) : '', fileSize = (file.size || 0) / 1000, j, msg,
  2543. fileExtExpr = '', previewData = $h.objUrl.createObjectURL(file), typ, chk, typ1, typ2,
  2544. fileCount = 0, strTypes = '', func;
  2545. if (typLen > 0) {
  2546. for (j = 0; j < typLen; j++) {
  2547. typ1 = fileTypes[j];
  2548. typ2 = self.msgFileTypes[typ1] || typ1;
  2549. strTypes += j === 0 ? typ2 : ', ' + typ2;
  2550. }
  2551. }
  2552. if (caption === false) {
  2553. readFile(i + 1);
  2554. return;
  2555. }
  2556. if (caption.length === 0) {
  2557. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name));
  2558. self.isError = throwError(msg, file, previewId, i);
  2559. return;
  2560. }
  2561. if (!$h.isEmpty(fileExt)) {
  2562. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2563. }
  2564. fSizeKB = fileSize.toFixed(2);
  2565. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2566. msg = self.msgSizeTooLarge.setTokens({
  2567. 'name': caption,
  2568. 'size': fSizeKB,
  2569. 'maxSize': self.maxFileSize
  2570. });
  2571. self.isError = throwError(msg, file, previewId, i);
  2572. return;
  2573. }
  2574. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  2575. msg = self.msgSizeTooSmall.setTokens({
  2576. 'name': caption,
  2577. 'size': fSizeKB,
  2578. 'minSize': self.minFileSize
  2579. });
  2580. self.isError = throwError(msg, file, previewId, i);
  2581. return;
  2582. }
  2583. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  2584. for (j = 0; j < fileTypes.length; j += 1) {
  2585. typ = fileTypes[j];
  2586. func = settings[typ];
  2587. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0);
  2588. }
  2589. if (fileCount === 0) {
  2590. msg = self.msgInvalidFileType.setTokens({'name': caption, 'types': strTypes});
  2591. self.isError = throwError(msg, file, previewId, i);
  2592. return;
  2593. }
  2594. }
  2595. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  2596. chk = $h.compare(caption, fileExtExpr);
  2597. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  2598. if (fileCount === 0) {
  2599. msg = self.msgInvalidFileExtension.setTokens({'name': caption, 'extensions': strExt});
  2600. self.isError = throwError(msg, file, previewId, i);
  2601. return;
  2602. }
  2603. }
  2604. if (!self.showPreview) {
  2605. self.addToStack(file);
  2606. setTimeout(function () {
  2607. readFile(i + 1);
  2608. }, 100);
  2609. self._raise('fileloaded', [file, previewId, i, reader]);
  2610. return;
  2611. }
  2612. if (!canPreview && fileSize > maxPreviewSize) {
  2613. self.addToStack(file);
  2614. $container.addClass('file-thumb-loading');
  2615. self._previewDefault(file, previewId);
  2616. self._initFileActions();
  2617. self._updateFileDetails(numFiles);
  2618. readFile(i + 1);
  2619. return;
  2620. }
  2621. if ($preview.length && FileReader !== undefined) {
  2622. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2623. $container.addClass('file-thumb-loading');
  2624. reader.onerror = function (evt) {
  2625. self._errorHandler(evt, caption);
  2626. };
  2627. reader.onload = function (theFile) {
  2628. self._previewFile(i, file, theFile, previewId, previewData);
  2629. self._initFileActions();
  2630. };
  2631. reader.onloadend = function () {
  2632. msg = msgProgress.setTokens({
  2633. 'index': i + 1,
  2634. 'files': numFiles,
  2635. 'percent': 50,
  2636. 'name': caption
  2637. });
  2638. setTimeout(function () {
  2639. $status.html(msg);
  2640. self._updateFileDetails(numFiles);
  2641. readFile(i + 1);
  2642. }, 100);
  2643. self._raise('fileloaded', [file, previewId, i, reader]);
  2644. };
  2645. reader.onprogress = function (data) {
  2646. if (data.lengthComputable) {
  2647. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2648. msg = msgProgress.setTokens({
  2649. 'index': i + 1,
  2650. 'files': numFiles,
  2651. 'percent': progress,
  2652. 'name': caption
  2653. });
  2654. setTimeout(function () {
  2655. $status.html(msg);
  2656. }, 100);
  2657. }
  2658. };
  2659. isText = settings.text;
  2660. isImage = settings.image;
  2661. if (isText(file.type, caption)) {
  2662. reader.readAsText(file, self.textEncoding);
  2663. } else {
  2664. if (isImage(file.type, caption)) {
  2665. reader.readAsDataURL(file);
  2666. } else {
  2667. reader.readAsArrayBuffer(file);
  2668. }
  2669. }
  2670. } else {
  2671. self._previewDefault(file, previewId);
  2672. setTimeout(function () {
  2673. readFile(i + 1);
  2674. self._updateFileDetails(numFiles);
  2675. }, 100);
  2676. self._raise('fileloaded', [file, previewId, i, reader]);
  2677. }
  2678. self.addToStack(file);
  2679. };
  2680. readFile(0);
  2681. self._updateFileDetails(numFiles, false);
  2682. },
  2683. _updateFileDetails: function (numFiles) {
  2684. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2685. name = ($h.isIE(9) && $h.findFileName($el.val())) ||
  2686. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2687. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2688. nFiles = self.previewCache.count() + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  2689. if (self.isError) {
  2690. self.$previewContainer.removeClass('file-thumb-loading');
  2691. self.$previewStatus.html('');
  2692. self.$captionContainer.find('.kv-caption-icon').hide();
  2693. } else {
  2694. self._showFileIcon();
  2695. }
  2696. self._setCaption(log, self.isError);
  2697. self.$container.removeClass('file-input-new file-input-ajax-new');
  2698. if (arguments.length === 1) {
  2699. self._raise('fileselect', [numFiles, label]);
  2700. }
  2701. if (self.previewCache.count()) {
  2702. self._initPreviewActions();
  2703. }
  2704. },
  2705. _setThumbStatus: function ($thumb, status) {
  2706. var self = this;
  2707. if (!self.showPreview) {
  2708. return;
  2709. }
  2710. var icon = 'indicator' + status, msg = icon + 'Title',
  2711. css = 'file-preview-' + status.toLowerCase(),
  2712. $indicator = $thumb.find('.file-upload-indicator'),
  2713. config = self.fileActionSettings;
  2714. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  2715. if (status === 'Error') {
  2716. $thumb.find('.kv-file-upload').attr('disabled', true);
  2717. }
  2718. if (status === 'Success') {
  2719. $thumb.find('.file-drag-handle').remove();
  2720. $indicator.css('margin-left', 0);
  2721. }
  2722. $indicator.html(config[icon]);
  2723. $indicator.attr('title', config[msg]);
  2724. $thumb.addClass(css);
  2725. },
  2726. _setProgressCancelled: function () {
  2727. var self = this;
  2728. self._setProgress(101, self.$progress, self.msgCancelled);
  2729. },
  2730. _setProgress: function (p, $el, error) {
  2731. var self = this, pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  2732. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  2733. template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : t);
  2734. $el = $el || self.$progress;
  2735. if (!$h.isEmpty(template)) {
  2736. if (pctLimit && pct > pctLimit && p <= 100) {
  2737. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  2738. } else {
  2739. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  2740. }
  2741. $el.html(out);
  2742. if (error) {
  2743. $el.find('[role="progressbar"]').html(error);
  2744. }
  2745. }
  2746. },
  2747. _setFileDropZoneTitle: function () {
  2748. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  2749. if (self.isClickable) {
  2750. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  2751. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  2752. }
  2753. $zone.find('.' + self.dropZoneTitleClass).remove();
  2754. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  2755. return;
  2756. }
  2757. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  2758. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  2759. }
  2760. self.$container.removeClass('file-input-new');
  2761. $h.addCss(self.$container, 'file-input-ajax-new');
  2762. },
  2763. _setAsyncUploadStatus: function (previewId, pct, total) {
  2764. var self = this, sum = 0;
  2765. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  2766. self.uploadStatus[previewId] = pct;
  2767. $.each(self.uploadStatus, function (key, value) {
  2768. sum += value;
  2769. });
  2770. self._setProgress(Math.floor(sum / total));
  2771. },
  2772. _validateMinCount: function () {
  2773. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2774. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  2775. self._noFilesError({});
  2776. return false;
  2777. }
  2778. return true;
  2779. },
  2780. _getFileCount: function (fileCount) {
  2781. var self = this, addCount = 0;
  2782. if (self.validateInitialCount && !self.overwriteInitial) {
  2783. addCount = self.previewCache.count();
  2784. fileCount += addCount;
  2785. }
  2786. return fileCount;
  2787. },
  2788. _getFileId: function (file) {
  2789. var self = this, custom = self.generateFileId, relativePath;
  2790. if (typeof custom === 'function') {
  2791. return custom(file, event);
  2792. }
  2793. if (!file) {
  2794. return null;
  2795. }
  2796. /** @namespace file.webkitRelativePath */
  2797. relativePath = file.webkitRelativePath || file.fileName || file.name || null;
  2798. if (!relativePath) {
  2799. return null;
  2800. }
  2801. return (file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
  2802. },
  2803. _getFileName: function (file) {
  2804. return file && file.name ? this.slug(file.name) : undefined;
  2805. },
  2806. _getFileIds: function (skipNull) {
  2807. var self = this;
  2808. return self.fileids.filter(function (n) {
  2809. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2810. });
  2811. },
  2812. _getFileNames: function (skipNull) {
  2813. var self = this;
  2814. return self.filenames.filter(function (n) {
  2815. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2816. });
  2817. },
  2818. _setPreviewError: function ($thumb, i, val) {
  2819. var self = this;
  2820. if (i !== undefined) {
  2821. self.updateStack(i, val);
  2822. }
  2823. if (self.removeFromPreviewOnError) {
  2824. $thumb.remove();
  2825. } else {
  2826. self._setThumbStatus($thumb, 'Error');
  2827. }
  2828. },
  2829. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2830. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  2831. $imgEl, isValid;
  2832. if ($h.isEmpty(limit) || !$img.length) {
  2833. return;
  2834. }
  2835. $imgEl = $img[0];
  2836. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2837. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2838. if (isValid) {
  2839. return;
  2840. }
  2841. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  2842. self._showUploadError(msg, params);
  2843. self._setPreviewError($thumb, i, null);
  2844. },
  2845. _validateImage: function (previewId, fname, ftype, fsize) {
  2846. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId),
  2847. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  2848. fname = fname || 'Untitled';
  2849. if (!$img.length) {
  2850. return;
  2851. }
  2852. self._handler($img, 'load', function () {
  2853. w1 = $thumb.width();
  2854. w2 = $preview.width();
  2855. if (w1 > w2) {
  2856. $img.css('width', '100%');
  2857. $thumb.css('width', '97%');
  2858. }
  2859. params = {ind: i, id: previewId};
  2860. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2861. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2862. if (!self.resizeImage) {
  2863. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2864. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2865. }
  2866. self._raise('fileimageloaded', [previewId]);
  2867. self.loadedImages.push({
  2868. ind: i,
  2869. img: $img,
  2870. thumb: $thumb,
  2871. pid: previewId,
  2872. typ: ftype,
  2873. siz: fsize,
  2874. validated: false
  2875. });
  2876. self._validateAllImages();
  2877. });
  2878. },
  2879. _validateAllImages: function () {
  2880. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length, config,
  2881. fsize, minSize = self.resizeIfSizeMoreThan;
  2882. if (numImgs !== self.totalImagesCount) {
  2883. return;
  2884. }
  2885. self._raise('fileimagesloaded');
  2886. if (!self.resizeImage) {
  2887. return;
  2888. }
  2889. for (i = 0; i < self.loadedImages.length; i++) {
  2890. config = self.loadedImages[i];
  2891. if (config.validated) {
  2892. continue;
  2893. }
  2894. fsize = config.siz;
  2895. if (fsize && fsize > minSize * 1000) {
  2896. self._getResizedImage(config, counter, numImgs);
  2897. }
  2898. self.loadedImages[i].validated = true;
  2899. }
  2900. },
  2901. _getResizedImage: function (config, counter, numImgs) {
  2902. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight,
  2903. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2904. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas,
  2905. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  2906. $thumb = config.thumb, throwError, msg;
  2907. throwError = function (msg, params, ev) {
  2908. if (self.isUploadable) {
  2909. self._showUploadError(msg, params, ev);
  2910. } else {
  2911. self._showError(msg, params, ev);
  2912. }
  2913. self._setPreviewError($thumb, ind);
  2914. };
  2915. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  2916. if (isValidImage && self.filestack[ind]) {
  2917. self._raise('fileimageresized', [pid, ind]);
  2918. }
  2919. counter.val++;
  2920. if (counter.val === numImgs) {
  2921. self._raise('fileimagesresized');
  2922. }
  2923. if (!isValidImage) {
  2924. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2925. return;
  2926. }
  2927. }
  2928. type = type || self.resizeDefaultImageType;
  2929. chkWidth = width > maxWidth;
  2930. chkHeight = height > maxHeight;
  2931. if (self.resizePreference === 'width') {
  2932. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2933. } else {
  2934. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2935. }
  2936. self._resetCanvas();
  2937. width *= ratio;
  2938. height *= ratio;
  2939. canvas.width = width;
  2940. canvas.height = height;
  2941. try {
  2942. context.drawImage(img, 0, 0, width, height);
  2943. canvas.toBlob(function (blob) {
  2944. self.filestack[ind] = blob;
  2945. self._raise('fileimageresized', [pid, ind]);
  2946. counter.val++;
  2947. if (counter.val === numImgs) {
  2948. self._raise('fileimagesresized', [undefined, undefined]);
  2949. }
  2950. if (!(blob instanceof Blob)) {
  2951. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2952. }
  2953. }, type, self.resizeQuality);
  2954. }
  2955. catch (err) {
  2956. counter.val++;
  2957. if (counter.val === numImgs) {
  2958. self._raise('fileimagesresized', [undefined, undefined]);
  2959. }
  2960. msg = self.msgImageResizeException.replace('{errors}', err.message);
  2961. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  2962. }
  2963. },
  2964. _initBrowse: function ($container) {
  2965. var self = this;
  2966. if (self.showBrowse) {
  2967. self.$btnFile = $container.find('.btn-file');
  2968. self.$btnFile.append(self.$element);
  2969. } else {
  2970. self.$element.hide();
  2971. }
  2972. },
  2973. _initCaption: function () {
  2974. var self = this, cap = self.initialCaption || '';
  2975. if (self.overwriteInitial || $h.isEmpty(cap)) {
  2976. self.$caption.html('');
  2977. return false;
  2978. }
  2979. self._setCaption(cap);
  2980. return true;
  2981. },
  2982. _setCaption: function (content, isError) {
  2983. var self = this, title, out, n, cap, stack = self.getFileStack();
  2984. if (!self.$caption.length) {
  2985. return;
  2986. }
  2987. if (isError) {
  2988. title = $('<div>' + self.msgValidationError + '</div>').text();
  2989. n = stack.length;
  2990. if (n) {
  2991. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2992. } else {
  2993. cap = self._getMsgSelected(self.msgNo);
  2994. }
  2995. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2996. ($h.isEmpty(content) ? cap : content) + '</span>';
  2997. } else {
  2998. if ($h.isEmpty(content)) {
  2999. return;
  3000. }
  3001. title = $('<div>' + content + '</div>').text();
  3002. out = self._getLayoutTemplate('fileIcon') + title;
  3003. }
  3004. self.$caption.html(out);
  3005. self.$caption.attr('title', title);
  3006. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  3007. },
  3008. _createContainer: function () {
  3009. var self = this, $container = $(document.createElement("div"))
  3010. .attr({"class": 'file-input file-input-new'})
  3011. .html(self._renderMain());
  3012. self.$element.before($container);
  3013. self._initBrowse($container);
  3014. if (self.theme) {
  3015. $container.addClass('theme-' + self.theme);
  3016. }
  3017. return $container;
  3018. },
  3019. _refreshContainer: function () {
  3020. var self = this, $container = self.$container;
  3021. $container.before(self.$element);
  3022. $container.html(self._renderMain());
  3023. self._initBrowse($container);
  3024. },
  3025. _renderMain: function () {
  3026. var self = this,
  3027. dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  3028. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  3029. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  3030. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  3031. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  3032. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  3033. return self.mainTemplate.setTokens({
  3034. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  3035. 'preview': preview,
  3036. 'close': close,
  3037. 'caption': caption,
  3038. 'upload': self._renderButton('upload'),
  3039. 'remove': self._renderButton('remove'),
  3040. 'cancel': self._renderButton('cancel'),
  3041. 'browse': self._renderButton('browse')
  3042. });
  3043. },
  3044. _renderButton: function (type) {
  3045. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  3046. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  3047. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  3048. switch (type) {
  3049. case 'remove':
  3050. if (!self.showRemove) {
  3051. return '';
  3052. }
  3053. break;
  3054. case 'cancel':
  3055. if (!self.showCancel) {
  3056. return '';
  3057. }
  3058. css += ' hide';
  3059. break;
  3060. case 'upload':
  3061. if (!self.showUpload) {
  3062. return '';
  3063. }
  3064. if (self.isUploadable && !self.isDisabled) {
  3065. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  3066. } else {
  3067. btnType = 'submit';
  3068. }
  3069. break;
  3070. case 'browse':
  3071. if (!self.showBrowse) {
  3072. return '';
  3073. }
  3074. tmplt = self._getLayoutTemplate('btnBrowse');
  3075. break;
  3076. default:
  3077. return '';
  3078. }
  3079. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  3080. if (!$h.isEmpty(label)) {
  3081. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  3082. }
  3083. return tmplt.setTokens({
  3084. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  3085. });
  3086. },
  3087. _renderThumbProgress: function () {
  3088. var self = this;
  3089. return '<div class="file-thumb-progress hide">' +
  3090. self.progressTemplate.setTokens({'percent': '0', 'status': self.msgUploadBegin}) +
  3091. '</div>';
  3092. },
  3093. _renderFileFooter: function (caption, size, width, isError) {
  3094. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  3095. upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'),
  3096. ind = isError ? config.indicatorError : config.indicatorNew,
  3097. tInd = self._getLayoutTemplate('indicator'),
  3098. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  3099. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  3100. size = self._getSize(size);
  3101. if (self.isUploadable) {
  3102. out = template.setTokens({
  3103. 'actions': self._renderFileActions(upl, rem, zoom, drg, false, false, false),
  3104. 'caption': caption,
  3105. 'size': size,
  3106. 'width': width,
  3107. 'progress': self._renderThumbProgress(),
  3108. 'indicator': indicator
  3109. });
  3110. } else {
  3111. out = template.setTokens({
  3112. 'actions': self._renderFileActions(false, false, zoom, drg, false, false, false),
  3113. 'caption': caption,
  3114. 'size': size,
  3115. 'width': width,
  3116. 'progress': '',
  3117. 'indicator': indicator
  3118. });
  3119. }
  3120. out = $h.replaceTags(out, self.previewThumbTags);
  3121. return out;
  3122. },
  3123. _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) {
  3124. if (!showUpload && !showDelete && !showZoom && !showDrag) {
  3125. return '';
  3126. }
  3127. var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"',
  3128. vKey = key === false ? '' : ' data-key="' + key + '"',
  3129. btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css,
  3130. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  3131. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey}),
  3132. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  3133. if (showDelete) {
  3134. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  3135. 'removeClass': removeClass,
  3136. 'removeIcon': config.removeIcon,
  3137. 'removeTitle': config.removeTitle,
  3138. 'dataUrl': vUrl,
  3139. 'dataKey': vKey
  3140. });
  3141. }
  3142. if (showUpload) {
  3143. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  3144. 'uploadClass': config.uploadClass,
  3145. 'uploadIcon': config.uploadIcon,
  3146. 'uploadTitle': config.uploadTitle
  3147. });
  3148. }
  3149. if (showZoom) {
  3150. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  3151. 'zoomClass': config.zoomClass,
  3152. 'zoomIcon': config.zoomIcon,
  3153. 'zoomTitle': config.zoomTitle
  3154. });
  3155. }
  3156. if (showDrag && isInit) {
  3157. css = 'drag-handle-init ' + config.dragClass;
  3158. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  3159. 'dragClass': css,
  3160. 'dragTitle': config.dragTitle,
  3161. 'dragIcon': config.dragIcon
  3162. });
  3163. }
  3164. return template.setTokens({
  3165. 'delete': btnDelete,
  3166. 'upload': btnUpload,
  3167. 'zoom': btnZoom,
  3168. 'drag': btnDrag,
  3169. 'other': otherButtons
  3170. });
  3171. },
  3172. _browse: function (e) {
  3173. var self = this;
  3174. self._raise('filebrowse');
  3175. if (e && e.isDefaultPrevented()) {
  3176. return;
  3177. }
  3178. if (self.isError && !self.isUploadable) {
  3179. self.clear();
  3180. }
  3181. self.$captionContainer.focus();
  3182. },
  3183. _filterDuplicate: function (file, files, fileIds) {
  3184. var self = this, fileId = self._getFileId(file);
  3185. if (fileId && fileIds && fileIds.indexOf(fileId) > -1) {
  3186. return;
  3187. }
  3188. if (!fileIds) {
  3189. fileIds = [];
  3190. }
  3191. files.push(file);
  3192. fileIds.push(fileId);
  3193. },
  3194. _change: function (e) {
  3195. var self = this, $el = self.$element;
  3196. if (!self.isUploadable && $h.isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  3197. self.fileInputCleared = false;
  3198. return;
  3199. }
  3200. self.fileInputCleared = false;
  3201. var tfiles = [], msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, n, len,
  3202. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  3203. isSingleUpload = $h.isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0),
  3204. folders = 0, fileIds = self._getFileIds(), throwError = function (mesg, file, previewId, index) {
  3205. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3206. p2 = {id: previewId, index: index, file: file, files: files};
  3207. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  3208. };
  3209. self.reader = null;
  3210. self._resetUpload();
  3211. self._hideFileIcon();
  3212. if (self.isUploadable) {
  3213. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  3214. }
  3215. if (isDragDrop) {
  3216. $.each(files, function (i, f) {
  3217. if (f && !f.type && f.size !== undefined && f.size % 4096 === 0) {
  3218. folders++;
  3219. } else {
  3220. self._filterDuplicate(f, tfiles, fileIds);
  3221. }
  3222. });
  3223. } else {
  3224. if (e.target && e.target.files === undefined) {
  3225. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  3226. } else {
  3227. files = e.target.files || {};
  3228. }
  3229. if (isAjaxUpload) {
  3230. $.each(files, function (i, f) {
  3231. self._filterDuplicate(f, tfiles, fileIds);
  3232. });
  3233. } else {
  3234. tfiles = files;
  3235. }
  3236. }
  3237. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  3238. if (!isAjaxUpload) {
  3239. self.clear();
  3240. }
  3241. self._showFolderError(folders);
  3242. self._raise('fileselectnone');
  3243. return;
  3244. }
  3245. self._resetErrors();
  3246. len = tfiles.length;
  3247. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  3248. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  3249. if (!self.autoReplace || len > self.maxFileCount) {
  3250. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  3251. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  3252. self.isError = throwError(msg, null, null, null);
  3253. self.$captionContainer.find('.kv-caption-icon').hide();
  3254. self._setCaption('', true);
  3255. self.$container.removeClass('file-input-new file-input-ajax-new');
  3256. return;
  3257. }
  3258. if (total > self.maxFileCount) {
  3259. self._resetPreviewThumbs(isAjaxUpload);
  3260. }
  3261. } else {
  3262. if (!isAjaxUpload || flagSingle) {
  3263. self._resetPreviewThumbs(false);
  3264. if (flagSingle) {
  3265. self.clearStack();
  3266. }
  3267. } else {
  3268. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  3269. self._resetPreviewThumbs(true);
  3270. }
  3271. }
  3272. }
  3273. if (self.isPreviewable) {
  3274. self._readFiles(tfiles);
  3275. } else {
  3276. self._updateFileDetails(1);
  3277. }
  3278. self._showFolderError(folders);
  3279. },
  3280. _abort: function (params) {
  3281. var self = this, data;
  3282. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  3283. data = $.extend(true, {}, self._getOutData(), params);
  3284. data.abortData = self.ajaxAborted.data || {};
  3285. data.abortMessage = self.ajaxAborted.message;
  3286. self._setProgress(101, self.$progress, self.msgCancelled);
  3287. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3288. self.cancel();
  3289. return true;
  3290. }
  3291. return false;
  3292. },
  3293. _resetFileStack: function () {
  3294. var self = this, i = 0, newstack = [], newnames = [], newids = [];
  3295. self._getThumbs().each(function () {
  3296. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind],
  3297. pid = $thumb.attr('id'), newId;
  3298. if (ind === '-1' || ind === -1) {
  3299. return;
  3300. }
  3301. if (file !== undefined) {
  3302. newstack[i] = file;
  3303. newnames[i] = self._getFileName(file);
  3304. newids[i] = self._getFileId(file);
  3305. $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
  3306. i++;
  3307. } else {
  3308. newId = 'uploaded-' + $h.uniqId();
  3309. $thumb.attr({'id': newId, 'data-fileindex': '-1'});
  3310. self.$preview.find('#zoom-' + pid).attr('id', 'zoom-' + newId);
  3311. }
  3312. });
  3313. self.filestack = newstack;
  3314. self.filenames = newnames;
  3315. self.fileids = newids;
  3316. },
  3317. clearStack: function () {
  3318. var self = this;
  3319. self.filestack = [];
  3320. self.filenames = [];
  3321. self.fileids = [];
  3322. return self.$element;
  3323. },
  3324. updateStack: function (i, file) {
  3325. var self = this;
  3326. self.filestack[i] = file;
  3327. self.filenames[i] = self._getFileName(file);
  3328. self.fileids[i] = file && self._getFileId(file) || null;
  3329. return self.$element;
  3330. },
  3331. addToStack: function (file) {
  3332. var self = this;
  3333. self.filestack.push(file);
  3334. self.filenames.push(self._getFileName(file));
  3335. self.fileids.push(self._getFileId(file));
  3336. return self.$element;
  3337. },
  3338. getFileStack: function (skipNull) {
  3339. var self = this;
  3340. return self.filestack.filter(function (n) {
  3341. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3342. });
  3343. },
  3344. getFilesCount: function () {
  3345. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  3346. return self._getFileCount(len);
  3347. },
  3348. lock: function () {
  3349. var self = this;
  3350. self._resetErrors();
  3351. self.disable();
  3352. if (self.showRemove) {
  3353. $h.addCss(self.$container.find('.fileinput-remove'), 'hide');
  3354. }
  3355. if (self.showCancel) {
  3356. self.$container.find('.fileinput-cancel').removeClass('hide');
  3357. }
  3358. self._raise('filelock', [self.filestack, self._getExtraData()]);
  3359. return self.$element;
  3360. },
  3361. unlock: function (reset) {
  3362. var self = this;
  3363. if (reset === undefined) {
  3364. reset = true;
  3365. }
  3366. self.enable();
  3367. if (self.showCancel) {
  3368. $h.addCss(self.$container.find('.fileinput-cancel'), 'hide');
  3369. }
  3370. if (self.showRemove) {
  3371. self.$container.find('.fileinput-remove').removeClass('hide');
  3372. }
  3373. if (reset) {
  3374. self._resetFileStack();
  3375. }
  3376. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  3377. return self.$element;
  3378. },
  3379. cancel: function () {
  3380. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  3381. if (len > 0) {
  3382. for (i = 0; i < len; i += 1) {
  3383. self.cancelling = true;
  3384. xhr[i].abort();
  3385. }
  3386. }
  3387. self._setProgressCancelled();
  3388. self._getThumbs().each(function () {
  3389. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  3390. $thumb.removeClass('file-uploading');
  3391. if (self.filestack[ind] !== undefined) {
  3392. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  3393. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  3394. }
  3395. self.unlock();
  3396. });
  3397. return self.$element;
  3398. },
  3399. clear: function () {
  3400. var self = this, cap;
  3401. if (!self._raise('fileclear')) {
  3402. return;
  3403. }
  3404. self.$btnUpload.removeAttr('disabled');
  3405. self._getThumbs().find('video,audio,img').each(function () {
  3406. $h.cleanMemory($(this));
  3407. });
  3408. self._resetUpload();
  3409. self.clearStack();
  3410. self._clearFileInput();
  3411. self._resetErrors(true);
  3412. if (self._hasInitialPreview()) {
  3413. self._showFileIcon();
  3414. self._resetPreview();
  3415. self._initPreviewActions();
  3416. self.$container.removeClass('file-input-new');
  3417. } else {
  3418. self._getThumbs().each(function () {
  3419. self._clearObjects($(this));
  3420. });
  3421. if (self.isUploadable) {
  3422. self.previewCache.data = {};
  3423. }
  3424. self.$preview.html('');
  3425. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  3426. self.$caption.html(cap);
  3427. self.$caption.attr('title', '');
  3428. $h.addCss(self.$container, 'file-input-new');
  3429. self._validateDefaultPreview();
  3430. }
  3431. if (self.$container.find($h.FRAMES).length === 0) {
  3432. if (!self._initCaption()) {
  3433. self.$captionContainer.find('.kv-caption-icon').hide();
  3434. }
  3435. }
  3436. self._hideFileIcon();
  3437. self._raise('filecleared');
  3438. self.$captionContainer.focus();
  3439. self._setFileDropZoneTitle();
  3440. return self.$element;
  3441. },
  3442. reset: function () {
  3443. var self = this;
  3444. if (!self._raise('filereset')) {
  3445. return;
  3446. }
  3447. self._resetPreview();
  3448. self.$container.find('.fileinput-filename').text('');
  3449. $h.addCss(self.$container, 'file-input-new');
  3450. if (self.$preview.find($h.FRAMES).length || self.isUploadable && self.dropZoneEnabled) {
  3451. self.$container.removeClass('file-input-new');
  3452. }
  3453. self._setFileDropZoneTitle();
  3454. self.clearStack();
  3455. self.formdata = {};
  3456. return self.$element;
  3457. },
  3458. disable: function () {
  3459. var self = this;
  3460. self.isDisabled = true;
  3461. self._raise('filedisabled');
  3462. self.$element.attr('disabled', 'disabled');
  3463. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  3464. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  3465. "disabled",
  3466. true);
  3467. self._initDragDrop();
  3468. return self.$element;
  3469. },
  3470. enable: function () {
  3471. var self = this;
  3472. self.isDisabled = false;
  3473. self._raise('fileenabled');
  3474. self.$element.removeAttr('disabled');
  3475. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  3476. self.$container.find(
  3477. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  3478. self._initDragDrop();
  3479. return self.$element;
  3480. },
  3481. upload: function () {
  3482. var self = this, totLen = self.getFileStack().length, params = {}, i, outData, len,
  3483. hasExtraData = !$.isEmptyObject(self._getExtraData());
  3484. if (!self.isUploadable || self.isDisabled) {
  3485. return;
  3486. }
  3487. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  3488. self._noFilesError(params);
  3489. return;
  3490. }
  3491. self._resetUpload();
  3492. if (totLen === 0 && !hasExtraData) {
  3493. self._showUploadError(self.msgUploadEmpty);
  3494. return;
  3495. }
  3496. self.$progress.removeClass('hide');
  3497. self.uploadCount = 0;
  3498. self.uploadStatus = {};
  3499. self.uploadLog = [];
  3500. self.lock();
  3501. self._setProgress(2);
  3502. if (totLen === 0 && hasExtraData) {
  3503. self._uploadExtraOnly();
  3504. return;
  3505. }
  3506. len = self.filestack.length;
  3507. self.hasInitData = false;
  3508. if (self.uploadAsync) {
  3509. outData = self._getOutData();
  3510. self._raise('filebatchpreupload', [outData]);
  3511. self.fileBatchCompleted = false;
  3512. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3513. self.uploadAsyncCount = self.getFileStack().length;
  3514. for (i = 0; i < len; i++) {
  3515. self.uploadCache.content[i] = null;
  3516. self.uploadCache.config[i] = null;
  3517. self.uploadCache.tags[i] = null;
  3518. }
  3519. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  3520. self._initSortable();
  3521. self.cacheInitialPreview = self.getPreview();
  3522. for (i = 0; i < len; i++) {
  3523. if (self.filestack[i] !== undefined) {
  3524. self._uploadSingle(i, self.filestack, true);
  3525. }
  3526. }
  3527. return;
  3528. }
  3529. self._uploadBatch();
  3530. return self.$element;
  3531. },
  3532. destroy: function () {
  3533. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  3534. $(document).off(ns);
  3535. $(window).off(ns);
  3536. if ($form && $form.length) {
  3537. $form.off(ns);
  3538. }
  3539. if (self.isUploadable) {
  3540. self._clearFileInput();
  3541. }
  3542. self._cleanup();
  3543. self._initPreviewCache();
  3544. $el.insertBefore($cont).off(ns).removeData();
  3545. $cont.off().remove();
  3546. return $el;
  3547. },
  3548. refresh: function (options) {
  3549. var self = this, $el = self.$element;
  3550. options = options ? $.extend(true, {}, self.options, options) : self.options;
  3551. self.destroy();
  3552. $el.fileinput(options);
  3553. self = $el.data('fileinput');
  3554. if (self.isUploadable) {
  3555. self._clearFileInput();
  3556. }
  3557. if ($el.val()) {
  3558. $el.trigger('change.fileinput');
  3559. }
  3560. return $el;
  3561. },
  3562. zoom: function (frameId) {
  3563. var self = this, $frame = $('#' + frameId), $modal = self.$modal;
  3564. if (!$frame.length) {
  3565. self._log('Cannot zoom to detailed preview! Invalid frame with id: "' + frameId + '".');
  3566. return;
  3567. }
  3568. $h.initModal($modal);
  3569. $modal.html(self._getModalContent());
  3570. self._setZoomContent($frame);
  3571. $modal.modal('show');
  3572. self._initZoomButtons();
  3573. },
  3574. getPreview: function () {
  3575. var self = this;
  3576. return {
  3577. content: self.initialPreview,
  3578. config: self.initialPreviewConfig,
  3579. tags: self.initialPreviewThumbTags
  3580. };
  3581. }
  3582. };
  3583. $.fn.fileinput = function (option) {
  3584. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  3585. return;
  3586. }
  3587. var args = Array.apply(null, arguments), retvals = [];
  3588. args.shift();
  3589. this.each(function () {
  3590. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  3591. theme = options.theme || self.data('theme'), l = {}, t = {},
  3592. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  3593. if (!data) {
  3594. if (theme) {
  3595. t = $.fn.fileinputThemes[theme] || {};
  3596. }
  3597. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  3598. l = $.fn.fileinputLocales[lang] || {};
  3599. }
  3600. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  3601. data = new FileInput(this, opt);
  3602. self.data('fileinput', data);
  3603. }
  3604. if (typeof option === 'string') {
  3605. retvals.push(data[option].apply(data, args));
  3606. }
  3607. });
  3608. switch (retvals.length) {
  3609. case 0:
  3610. return this;
  3611. case 1:
  3612. return retvals[0];
  3613. default:
  3614. return retvals;
  3615. }
  3616. };
  3617. $.fn.fileinput.defaults = {
  3618. language: 'en',
  3619. showCaption: true,
  3620. showBrowse: true,
  3621. showPreview: true,
  3622. showRemove: true,
  3623. showUpload: true,
  3624. showCancel: true,
  3625. showClose: true,
  3626. showUploadedThumbs: true,
  3627. browseOnZoneClick: false,
  3628. autoReplace: false,
  3629. autoOrientImage: true, // for JPEG images based on EXIF orientation tag
  3630. generateFileId: null,
  3631. previewClass: '',
  3632. captionClass: '',
  3633. frameClass: 'krajee-default',
  3634. mainClass: 'file-caption-main',
  3635. mainTemplate: null,
  3636. purifyHtml: true,
  3637. fileSizeGetter: null,
  3638. initialCaption: '',
  3639. initialPreview: [],
  3640. initialPreviewDelimiter: '*$$*',
  3641. initialPreviewAsData: false,
  3642. initialPreviewFileType: 'image',
  3643. initialPreviewConfig: [],
  3644. initialPreviewThumbTags: [],
  3645. previewThumbTags: {},
  3646. initialPreviewShowDelete: true,
  3647. removeFromPreviewOnError: false,
  3648. deleteUrl: '',
  3649. deleteExtraData: {},
  3650. overwriteInitial: true,
  3651. previewZoomButtonIcons: {
  3652. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  3653. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  3654. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  3655. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  3656. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  3657. close: '<i class="glyphicon glyphicon-remove"></i>'
  3658. },
  3659. previewZoomButtonClasses: {
  3660. prev: 'btn btn-navigate',
  3661. next: 'btn btn-navigate',
  3662. toggleheader: 'btn btn-default btn-header-toggle',
  3663. fullscreen: 'btn btn-default',
  3664. borderless: 'btn btn-default',
  3665. close: 'btn btn-default'
  3666. },
  3667. preferIconicPreview: false,
  3668. preferIconicZoomPreview: false,
  3669. allowedPreviewTypes: undefined,
  3670. allowedPreviewMimeTypes: null,
  3671. allowedFileTypes: null,
  3672. allowedFileExtensions: null,
  3673. defaultPreviewContent: null,
  3674. customLayoutTags: {},
  3675. customPreviewTags: {},
  3676. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  3677. previewFileIconClass: 'file-other-icon',
  3678. previewFileIconSettings: {},
  3679. previewFileExtSettings: {},
  3680. buttonLabelClass: 'hidden-xs',
  3681. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  3682. browseClass: 'btn btn-primary',
  3683. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  3684. removeClass: 'btn btn-default',
  3685. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  3686. cancelClass: 'btn btn-default',
  3687. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  3688. uploadClass: 'btn btn-default',
  3689. uploadUrl: null,
  3690. uploadAsync: true,
  3691. uploadExtraData: {},
  3692. zoomModalHeight: 480,
  3693. minImageWidth: null,
  3694. minImageHeight: null,
  3695. maxImageWidth: null,
  3696. maxImageHeight: null,
  3697. resizeImage: false,
  3698. resizePreference: 'width',
  3699. resizeQuality: 0.92,
  3700. resizeDefaultImageType: 'image/jpeg',
  3701. resizeIfSizeMoreThan: 0, // in KB
  3702. minFileSize: 0,
  3703. maxFileSize: 0,
  3704. maxFilePreviewSize: 25600, // 25 MB
  3705. minFileCount: 0,
  3706. maxFileCount: 0,
  3707. validateInitialCount: false,
  3708. msgValidationErrorClass: 'text-danger',
  3709. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  3710. msgErrorClass: 'file-error-message',
  3711. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  3712. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  3713. progressCompleteClass: "progress-bar progress-bar-success",
  3714. progressErrorClass: "progress-bar progress-bar-danger",
  3715. progressUploadThreshold: 99,
  3716. previewFileType: 'image',
  3717. elCaptionContainer: null,
  3718. elCaptionText: null,
  3719. elPreviewContainer: null,
  3720. elPreviewImage: null,
  3721. elPreviewStatus: null,
  3722. elErrorContainer: null,
  3723. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  3724. slugCallback: null,
  3725. dropZoneEnabled: true,
  3726. dropZoneTitleClass: 'file-drop-zone-title',
  3727. fileActionSettings: {},
  3728. otherActionButtons: '',
  3729. textEncoding: 'UTF-8',
  3730. ajaxSettings: {},
  3731. ajaxDeleteSettings: {},
  3732. showAjaxErrorDetails: true
  3733. };
  3734. $.fn.fileinputLocales.en = {
  3735. fileSingle: 'file',
  3736. filePlural: 'files',
  3737. browseLabel: 'Browse &hellip;',
  3738. removeLabel: 'Remove',
  3739. removeTitle: 'Clear selected files',
  3740. cancelLabel: 'Cancel',
  3741. cancelTitle: 'Abort ongoing upload',
  3742. uploadLabel: 'Upload',
  3743. uploadTitle: 'Upload selected files',
  3744. msgNo: 'No',
  3745. msgNoFilesSelected: 'No files selected',
  3746. msgCancelled: 'Cancelled',
  3747. msgZoomModalHeading: 'Detailed Preview',
  3748. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  3749. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  3750. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  3751. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  3752. msgFileNotFound: 'File "{name}" not found!',
  3753. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  3754. msgFileNotReadable: 'File "{name}" is not readable.',
  3755. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  3756. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  3757. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  3758. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  3759. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  3760. msgFileTypes: {
  3761. 'image': 'image',
  3762. 'html': 'HTML',
  3763. 'text': 'text',
  3764. 'video': 'video',
  3765. 'audio': 'audio',
  3766. 'flash': 'flash',
  3767. 'pdf': 'PDF',
  3768. 'object': 'object'
  3769. },
  3770. msgUploadAborted: 'The file upload was aborted',
  3771. msgUploadThreshold: 'Processing...',
  3772. msgUploadBegin: 'Initializing...',
  3773. msgUploadEnd: 'Done',
  3774. msgUploadEmpty: 'No valid data available for upload.',
  3775. msgValidationError: 'Validation Error',
  3776. msgLoading: 'Loading file {index} of {files} &hellip;',
  3777. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  3778. msgSelected: '{n} {files} selected',
  3779. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  3780. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  3781. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  3782. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  3783. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  3784. msgImageResizeError: 'Could not get the image dimensions to resize.',
  3785. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  3786. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  3787. msgAjaxProgressError: '{operation} failed',
  3788. ajaxOperations: {
  3789. deleteThumb: 'file delete',
  3790. uploadThumb: 'file upload',
  3791. uploadBatch: 'batch file upload',
  3792. uploadExtra: 'form data upload'
  3793. },
  3794. dropZoneTitle: 'Drag & drop files here &hellip;',
  3795. dropZoneClickTitle: '<br>(or click to select {files})',
  3796. previewZoomButtonTitles: {
  3797. prev: 'View previous file',
  3798. next: 'View next file',
  3799. toggleheader: 'Toggle header',
  3800. fullscreen: 'Toggle full screen',
  3801. borderless: 'Toggle borderless mode',
  3802. close: 'Close detailed preview'
  3803. }
  3804. };
  3805. $.fn.fileinput.Constructor = FileInput;
  3806. /**
  3807. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  3808. */
  3809. $(document).ready(function () {
  3810. var $input = $('input.file[type=file]');
  3811. if ($input.length) {
  3812. $input.fileinput();
  3813. }
  3814. });
  3815. }));