fileinput.js 148 KB

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