fileinput.js 146 KB

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