fileinput.js 126 KB

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