fileinput.js 148 KB

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