fileinput.js 145 KB

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