fileinput.js 150 KB

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