fileinput.js 146 KB

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