fileinput.js 169 KB

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