fileinput.js 163 KB

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