fileinput.js 127 KB

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