fileinput.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.2.5
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API.
  7. *
  8. * The plugin drastically enhances the HTML file input to preview multiple files on the client before
  9. * upload. In addition it provides the ability to preview content of images, text, videos, audio, html,
  10. * flash and other objects. It also offers the ability to upload and delete files using AJAX, and add
  11. * files in batches (i.e. preview, append, or remove before upload).
  12. *
  13. * Author: Kartik Visweswaran
  14. * Copyright: 2015, Kartik Visweswaran, Krajee.com
  15. * For more JQuery plugins visit http://plugins.krajee.com
  16. * For more Yii related demos visit http://demos.krajee.com
  17. */
  18. (function ($) {
  19. "use strict";
  20. $.fn.fileinputLocales = {};
  21. String.prototype.repl = function (from, to) {
  22. return this.split(from).join(to);
  23. };
  24. var isIE = function (ver) {
  25. var div = document.createElement("div"), status;
  26. div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->";
  27. status = (div.getElementsByTagName("i").length === 1);
  28. document.body.appendChild(div);
  29. div.parentNode.removeChild(div);
  30. return status;
  31. },
  32. handler = function ($el, event, callback, skipNS) {
  33. var ev = skipNS ? event : event + '.fileinput';
  34. $el.off(ev).on(ev, callback);
  35. },
  36. previewCache = {
  37. data: {},
  38. init: function (obj) {
  39. var content = obj.initialPreview, id = obj.id;
  40. if (content.length > 0 && !isArray(content)) {
  41. content = content.split(obj.initialPreviewDelimiter);
  42. }
  43. previewCache.data[id] = {
  44. content: content,
  45. config: obj.initialPreviewConfig,
  46. tags: obj.initialPreviewThumbTags,
  47. delimiter: obj.initialPreviewDelimiter,
  48. template: obj.previewGenericTemplate,
  49. msg: function (n) {
  50. return obj.getMsgSelected(n);
  51. },
  52. initId: obj.previewInitId,
  53. footer: obj.getLayoutTemplate('footer'),
  54. isDelete: obj.initialPreviewShowDelete,
  55. caption: obj.initialCaption,
  56. actions: function (showUpload, showDelete, disabled, url, key) {
  57. return obj.renderFileActions(showUpload, showDelete, disabled, url, key);
  58. }
  59. };
  60. },
  61. fetch: function (id) {
  62. return previewCache.data[id].content.filter(function (n) {
  63. return n !== null;
  64. });
  65. },
  66. count: function (id, all) {
  67. return !!previewCache.data[id] && !!previewCache.data[id].content ?
  68. (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0;
  69. },
  70. get: function (id, i, isDisabled) {
  71. var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i],
  72. previewId = data.initId + '-' + ind, out, $tmp, frameAttr = {},
  73. frameClass = ' file-preview-initial';
  74. isDisabled = isDisabled === undefined ? true : isDisabled;
  75. if (data.content[i] === null) {
  76. return '';
  77. }
  78. if (!isEmpty(config) && !isEmpty(config.frameClass)) {
  79. frameClass += ' ' + config.frameClass;
  80. }
  81. out = data.template
  82. .repl('{previewId}', previewId)
  83. .repl('{frameClass}', frameClass)
  84. .repl('{fileindex}', ind)
  85. .repl('{content}', data.content[i])
  86. .repl('{footer}', previewCache.footer(id, i, isDisabled));
  87. if (data.tags.length && data.tags[i]) {
  88. out = replaceTags(out, data.tags[i]);
  89. }
  90. if (!isEmpty(config) && !isEmpty(config.frameAttr)) {
  91. $tmp = $(document.createElement('div')).html(out);
  92. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  93. out = $tmp.html();
  94. $tmp.remove();
  95. }
  96. return out;
  97. },
  98. add: function (id, content, config, tags, append) {
  99. var data = $.extend(true, {}, previewCache.data[id]), index;
  100. if (!isArray(content)) {
  101. content = content.split(data.delimiter);
  102. }
  103. if (append) {
  104. index = data.content.push(content) - 1;
  105. data.config[index] = config;
  106. data.tags[index] = tags;
  107. } else {
  108. index = content.length;
  109. data.content = content;
  110. data.config = config;
  111. data.tags = tags;
  112. }
  113. previewCache.data[id] = data;
  114. return index;
  115. },
  116. set: function (id, content, config, tags, append) {
  117. var data = $.extend(true, {}, previewCache.data[id]), i;
  118. if (!isArray(content)) {
  119. content = content.split(data.delimiter);
  120. }
  121. if (append) {
  122. for (i = 0; i < content.length; i++) {
  123. data.content.push(content[i]);
  124. }
  125. for (i = 0; i < config.length; i++) {
  126. data.config.push(config[i]);
  127. }
  128. for (i = 0; i < tags.length; i++) {
  129. data.tags.push(tags[i]);
  130. }
  131. } else {
  132. data.content = content;
  133. data.config = config;
  134. data.tags = tags;
  135. }
  136. previewCache.data[id] = data;
  137. },
  138. unset: function (id, index) {
  139. var chk = previewCache.count(id);
  140. if (!chk) {
  141. return;
  142. }
  143. if (chk === 1) {
  144. previewCache.data[id].content = [];
  145. previewCache.data[id].config = [];
  146. return;
  147. }
  148. previewCache.data[id].content[index] = null;
  149. previewCache.data[id].config[index] = null;
  150. },
  151. out: function (id) {
  152. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true);
  153. if (len === 0) {
  154. return {content: '', caption: ''};
  155. }
  156. for (var i = 0; i < len; i++) {
  157. html += previewCache.get(id, i);
  158. }
  159. caption = data.msg(previewCache.count(id));
  160. return {content: html, caption: caption};
  161. },
  162. footer: function (id, i, isDisabled) {
  163. var data = previewCache.data[id];
  164. isDisabled = isDisabled === undefined ? true : isDisabled;
  165. if (data.config.length === 0 || isEmpty(data.config[i])) {
  166. return '';
  167. }
  168. var config = data.config[i],
  169. caption = isSet('caption', config) ? config.caption : '',
  170. width = isSet('width', config) ? config.width : 'auto',
  171. url = isSet('url', config) ? config.url : false,
  172. key = isSet('key', config) ? config.key : null,
  173. disabled = (url === false) && isDisabled,
  174. actions = data.isDelete ? data.actions(false, true, disabled, url, key) : '',
  175. footer = data.footer.repl('{actions}', actions);
  176. return footer
  177. .repl('{caption}', caption)
  178. .repl('{width}', width)
  179. .repl('{indicator}', '')
  180. .repl('{indicatorTitle}', '');
  181. }
  182. },
  183. getNum = function (num, def) {
  184. def = def || 0;
  185. if (typeof num === "number") {
  186. return num;
  187. }
  188. if (typeof num === "string") {
  189. num = parseFloat(num);
  190. }
  191. return isNaN(num) ? def : num;
  192. },
  193. hasFileAPISupport = function () {
  194. return window.File && window.FileReader;
  195. },
  196. hasDragDropSupport = function () {
  197. var $div = document.createElement('div');
  198. return !isIE(9) && ($div.draggable !== undefined || ($div.ondragstart !== undefined && $div.ondrop !== undefined));
  199. },
  200. hasFileUploadSupport = function () {
  201. return hasFileAPISupport() && window.FormData;
  202. },
  203. addCss = function ($el, css) {
  204. $el.removeClass(css).addClass(css);
  205. },
  206. STYLE_SETTING = 'style="width:{width};height:{height};"',
  207. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  208. ' <param name="allowFullScreen" value="true" />\n' +
  209. ' <param name="allowScriptAccess" value="always" />\n' +
  210. ' <param name="autoPlay" value="false" />\n' +
  211. ' <param name="autoStart" value="false" />\n' +
  212. ' <param name="quality" value="high" />\n',
  213. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  214. ' {previewFileIcon}\n' +
  215. ' </div>',
  216. defaultFileActionSettings = {
  217. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  218. removeClass: 'btn btn-xs btn-default',
  219. removeTitle: 'Remove file',
  220. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  221. uploadClass: 'btn btn-xs btn-default',
  222. uploadTitle: 'Upload file',
  223. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  224. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>',
  225. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  226. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  227. indicatorNewTitle: 'Not uploaded yet',
  228. indicatorSuccessTitle: 'Uploaded',
  229. indicatorErrorTitle: 'Upload Error',
  230. indicatorLoadingTitle: 'Uploading ...'
  231. },
  232. tMain1 = '{preview}\n' +
  233. '<div class="kv-upload-progress hide"></div>\n' +
  234. '<div class="input-group {class}">\n' +
  235. ' {caption}\n' +
  236. ' <div class="input-group-btn">\n' +
  237. ' {remove}\n' +
  238. ' {cancel}\n' +
  239. ' {upload}\n' +
  240. ' {browse}\n' +
  241. ' </div>\n' +
  242. '</div>',
  243. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  244. tPreview = '<div class="file-preview {class}">\n' +
  245. ' <div class="close fileinput-remove">&times;</div>\n' +
  246. ' <div class="{dropClass}">\n' +
  247. ' <div class="file-preview-thumbnails">\n' +
  248. ' </div>\n' +
  249. ' <div class="clearfix"></div>' +
  250. ' <div class="file-preview-status text-center text-success"></div>\n' +
  251. ' <div class="kv-fileinput-error"></div>\n' +
  252. ' </div>\n' +
  253. '</div>',
  254. tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  255. tCaption = '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  256. ' <span class="file-caption-ellipsis">&hellip;</span>\n' +
  257. ' <div class="file-caption-name"></div>\n' +
  258. '</div>',
  259. tModal = '<div id="{id}" class="modal fade">\n' +
  260. ' <div class="modal-dialog modal-lg">\n' +
  261. ' <div class="modal-content">\n' +
  262. ' <div class="modal-header">\n' +
  263. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  264. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  265. ' </div>\n' +
  266. ' <div class="modal-body">\n' +
  267. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  268. ' </div>\n' +
  269. ' </div>\n' +
  270. ' </div>\n' +
  271. '</div>',
  272. tProgress = '<div class="progress">\n' +
  273. ' <div class="{class}" role="progressbar"' +
  274. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  275. ' {percent}%\n' +
  276. ' </div>\n' +
  277. '</div>',
  278. tFooter = '<div class="file-thumbnail-footer">\n' +
  279. ' <div class="file-caption-name">{caption}</div>\n' +
  280. ' {actions}\n' +
  281. '</div>',
  282. tActions = '<div class="file-actions">\n' +
  283. ' <div class="file-footer-buttons">\n' +
  284. ' {upload}{delete}{other}' +
  285. ' </div>\n' +
  286. ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
  287. ' <div class="clearfix"></div>\n' +
  288. '</div>',
  289. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  290. 'title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  291. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  292. ' {uploadIcon}\n</button>\n',
  293. tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  294. ' {content}\n' +
  295. ' {footer}\n' +
  296. '</div>\n',
  297. tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  298. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  299. ' ' + DEFAULT_PREVIEW + '\n' +
  300. ' </object>\n' +
  301. ' {footer}\n' +
  302. '</div>',
  303. tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  304. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  305. ' {footer}\n' +
  306. '</div>\n',
  307. tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  308. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  309. ' {data}\n' +
  310. ' </div>\n' +
  311. ' {footer}\n' +
  312. '</div>',
  313. tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  314. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  315. ' <video width="{width}" height="{height}" controls>\n' +
  316. ' <source src="{data}" type="{type}">\n' +
  317. ' ' + DEFAULT_PREVIEW + '\n' +
  318. ' </video>\n' +
  319. ' {footer}\n' +
  320. '</div>\n',
  321. tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  322. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  323. ' <audio controls>\n' +
  324. ' <source src="' + '{data}' + '" type="{type}">\n' +
  325. ' ' + DEFAULT_PREVIEW + '\n' +
  326. ' </audio>\n' +
  327. ' {footer}\n' +
  328. '</div>',
  329. tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  330. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  331. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  332. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  333. ' </object>\n' +
  334. ' {footer}\n' +
  335. '</div>\n',
  336. tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  337. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  338. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  339. ' <param name="movie" value="{caption}" />\n' +
  340. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  341. ' </object>\n' +
  342. ' {footer}\n' +
  343. '</div>',
  344. tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  345. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  346. ' ' + DEFAULT_PREVIEW + '\n' +
  347. ' {footer}\n' +
  348. '</div>',
  349. defaultLayoutTemplates = {
  350. main1: tMain1,
  351. main2: tMain2,
  352. preview: tPreview,
  353. icon: tIcon,
  354. caption: tCaption,
  355. modal: tModal,
  356. progress: tProgress,
  357. footer: tFooter,
  358. actions: tActions,
  359. actionDelete: tActionDelete,
  360. actionUpload: tActionUpload
  361. },
  362. defaultPreviewTemplates = {
  363. generic: tGeneric,
  364. html: tHtml,
  365. image: tImage,
  366. text: tText,
  367. video: tVideo,
  368. audio: tAudio,
  369. flash: tFlash,
  370. object: tObject,
  371. other: tOther
  372. },
  373. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
  374. defaultPreviewSettings = {
  375. image: {width: "auto", height: "160px"},
  376. html: {width: "213px", height: "160px"},
  377. text: {width: "160px", height: "160px"},
  378. video: {width: "213px", height: "160px"},
  379. audio: {width: "213px", height: "80px"},
  380. flash: {width: "213px", height: "160px"},
  381. object: {width: "160px", height: "160px"},
  382. other: {width: "160px", height: "160px"}
  383. },
  384. defaultFileTypeSettings = {
  385. image: function (vType, vName) {
  386. return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  387. },
  388. html: function (vType, vName) {
  389. return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i);
  390. },
  391. text: function (vType, vName) {
  392. return (vType !== undefined && vType.match('text.*')) || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  393. },
  394. video: function (vType, vName) {
  395. return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm)$/i)) || vName.match(/\.(og?|mp4|webm)$/i);
  396. },
  397. audio: function (vType, vName) {
  398. return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  399. },
  400. flash: function (vType, vName) {
  401. return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  402. },
  403. object: function () {
  404. return true;
  405. },
  406. other: function () {
  407. return true;
  408. }
  409. },
  410. isEmpty = function (value, trim) {
  411. return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === '');
  412. },
  413. isArray = function (a) {
  414. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  415. },
  416. isSet = function (needle, haystack) {
  417. return (typeof haystack === 'object' && needle in haystack);
  418. },
  419. getElement = function (options, param, value) {
  420. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  421. },
  422. uniqId = function () {
  423. return Math.round(new Date().getTime() + (Math.random() * 100));
  424. },
  425. htmlEncode = function (str) {
  426. return String(str).repl('&', '&amp;')
  427. .repl('"', '&quot;')
  428. .repl("'", '&#39;')
  429. .repl('<', '&lt;')
  430. .repl('>', '&gt;');
  431. },
  432. replaceTags = function (str, tags) {
  433. var out = str;
  434. tags = tags || {};
  435. $.each(tags, function (key, value) {
  436. if (typeof value === "function") {
  437. value = value();
  438. }
  439. out = out.repl(key, value);
  440. });
  441. return out;
  442. },
  443. objUrl = window.URL || window.webkitURL,
  444. FileInput = function (element, options) {
  445. var self = this;
  446. self.$element = $(element);
  447. if (!self.validate()) {
  448. return;
  449. }
  450. self.isPreviewable = hasFileAPISupport();
  451. self.isIE9 = isIE(9);
  452. self.isIE10 = isIE(10);
  453. if (self.isPreviewable || self.isIE9) {
  454. self.init(options);
  455. self.listen();
  456. } else {
  457. self.$element.removeClass('file-loading');
  458. }
  459. };
  460. FileInput.prototype = {
  461. constructor: FileInput,
  462. validate: function () {
  463. var self = this, $exception;
  464. if (self.$element.attr('type') === 'file') {
  465. return true;
  466. }
  467. $exception = '<div class="help-block alert alert-warning">' +
  468. '<h4>Invalid Input Type</h4>' +
  469. 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' +
  470. '</div>';
  471. self.$element.after($exception);
  472. return false;
  473. },
  474. init: function (options) {
  475. var self = this, $el = self.$element, t;
  476. $.each(options, function (key, value) {
  477. self[key] = (key === 'maxFileCount' || key === 'maxFileSize') ? getNum(value) : value;
  478. });
  479. self.fileInputCleared = false;
  480. self.fileBatchCompleted = true;
  481. if (isEmpty(self.allowedPreviewTypes)) {
  482. self.allowedPreviewTypes = defaultPreviewTypes;
  483. }
  484. if (!self.isPreviewable) {
  485. self.showPreview = false;
  486. }
  487. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  488. self.reader = null;
  489. self.formdata = {};
  490. self.filestack = [];
  491. self.ajaxRequests = [];
  492. self.isError = false;
  493. self.ajaxAborted = false;
  494. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  495. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  496. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  497. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  498. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  499. self.captionTemplate = self.getLayoutTemplate('caption');
  500. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  501. if (isEmpty(self.$element.attr('id'))) {
  502. self.$element.attr('id', uniqId());
  503. }
  504. if (self.$container === undefined) {
  505. self.$container = self.createContainer();
  506. } else {
  507. self.refreshContainer();
  508. }
  509. self.$progress = self.$container.find('.kv-upload-progress');
  510. self.$btnUpload = self.$container.find('.kv-fileinput-upload');
  511. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  512. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  513. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  514. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  515. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  516. self.$errorContainer = getElement(options, 'elErrorContainer',
  517. self.$previewContainer.find('.kv-fileinput-error'));
  518. if (!isEmpty(self.msgErrorClass)) {
  519. addCss(self.$errorContainer, self.msgErrorClass);
  520. }
  521. self.$errorContainer.hide();
  522. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  523. self.previewInitId = "preview-" + uniqId();
  524. self.id = self.$element.attr('id');
  525. previewCache.init(self);
  526. self.initPreview(true);
  527. self.initPreviewDeletes();
  528. self.options = options;
  529. self.setFileDropZoneTitle();
  530. self.uploadCount = 0;
  531. self.uploadPercent = 0;
  532. self.$element.removeClass('file-loading');
  533. t = self.getLayoutTemplate('progress');
  534. self.progressTemplate = t.replace('{class}', self.progressClass);
  535. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  536. self.setEllipsis();
  537. },
  538. parseError: function (jqXHR, errorThrown, fileName) {
  539. var self = this, errMsg = $.trim(errorThrown + ''),
  540. dot = errMsg.slice(-1) === '.' ? '' : '.',
  541. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  542. jqXHR.responseJSON.error : jqXHR.responseText;
  543. if (self.showAjaxErrorDetails) {
  544. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  545. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  546. errMsg += dot + text;
  547. } else {
  548. errMsg += dot;
  549. }
  550. return fileName ? '<b>' + fileName + ': </b>' + jqXHR : errMsg;
  551. },
  552. raise: function (event, params) {
  553. var self = this, e = $.Event(event);
  554. if (params !== undefined) {
  555. self.$element.trigger(e, params);
  556. } else {
  557. self.$element.trigger(e);
  558. }
  559. if (!e.result) {
  560. return e.result;
  561. }
  562. switch (event) {
  563. // ignore these events
  564. case 'filebatchuploadcomplete':
  565. case 'filebatchuploadsuccess':
  566. case 'fileuploaded':
  567. case 'fileclear':
  568. case 'filecleared':
  569. case 'filereset':
  570. case 'fileerror':
  571. case 'filefoldererror':
  572. case 'fileuploaderror':
  573. case 'filebatchuploaderror':
  574. case 'filedeleteerror':
  575. case 'filecustomerror':
  576. case 'filesuccessremove':
  577. break;
  578. // receive data response via `filecustomerror` event`
  579. default:
  580. self.ajaxAborted = e.result;
  581. break;
  582. }
  583. return true;
  584. },
  585. getLayoutTemplate: function (t) {
  586. var self = this,
  587. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  588. if (isEmpty(self.customLayoutTags)) {
  589. return template;
  590. }
  591. return replaceTags(template, self.customLayoutTags);
  592. },
  593. getPreviewTemplate: function (t) {
  594. var self = this,
  595. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  596. template = template.repl('{previewFileIcon}', self.previewFileIcon);
  597. if (isEmpty(self.customPreviewTags)) {
  598. return template;
  599. }
  600. return replaceTags(template, self.customPreviewTags);
  601. },
  602. getOutData: function (jqXHR, responseData, filesData) {
  603. var self = this;
  604. jqXHR = jqXHR || {};
  605. responseData = responseData || {};
  606. filesData = filesData || self.filestack.slice(0) || {};
  607. return {
  608. form: self.formdata,
  609. files: filesData,
  610. extra: self.getExtraData(),
  611. response: responseData,
  612. reader: self.reader,
  613. jqXHR: jqXHR
  614. };
  615. },
  616. setEllipsis: function () {
  617. var self = this, $capCont = self.$captionContainer, $cap = self.$caption,
  618. $div = $cap.clone().css('height', 'auto').hide();
  619. $capCont.parent().before($div);
  620. $capCont.removeClass('kv-has-ellipsis');
  621. if ($div.outerWidth() > $cap.outerWidth()) {
  622. $capCont.addClass('kv-has-ellipsis');
  623. }
  624. $div.remove();
  625. },
  626. listen: function () {
  627. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile,
  628. $form = $el.closest('form'), $cont = self.$container;
  629. handler($el, 'change', $.proxy(self.change, self));
  630. handler($(window), 'resize', function () {
  631. self.setEllipsis();
  632. });
  633. handler($btnFile, 'click', function () {
  634. self.raise('filebrowse');
  635. if (self.isError && !self.isUploadable) {
  636. self.clear();
  637. }
  638. $cap.focus();
  639. });
  640. handler($form, 'reset', $.proxy(self.reset, self));
  641. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  642. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  643. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  644. self.initDragDrop();
  645. }
  646. if (!self.isUploadable) {
  647. handler($form, 'submit', $.proxy(self.submitForm, self));
  648. }
  649. handler(self.$container.find('.kv-fileinput-upload'), 'click', function (e) {
  650. var $btn = $(this), $form, isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  651. if (!self.isUploadable) {
  652. if (isEnabled && $btn.attr('type') !== 'submit') {
  653. $form = $btn.closest('form');
  654. // downgrade to normal form submit if possible
  655. if ($form.length) {
  656. $form.trigger('submit');
  657. }
  658. e.preventDefault();
  659. }
  660. return;
  661. }
  662. e.preventDefault();
  663. if (isEnabled) {
  664. self.upload();
  665. }
  666. });
  667. },
  668. submitForm: function () {
  669. var self = this, $el = self.$element, files = $el.get(0).files;
  670. if (files && files.length < self.minFileCount && self.minFileCount > 0) {
  671. self.noFilesError({});
  672. return false;
  673. }
  674. return !self.abort({});
  675. },
  676. abort: function (params) {
  677. var self = this, data;
  678. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  679. data = $.extend(self.getOutData(), params);
  680. data.abortData = self.ajaxAborted.data || {};
  681. data.abortMessage = self.ajaxAborted.message;
  682. self.showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  683. return true;
  684. }
  685. return false;
  686. },
  687. noFilesError: function (params) {
  688. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  689. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  690. $error = self.$errorContainer;
  691. $error.html(msg);
  692. self.isError = true;
  693. self.updateFileDetails(0);
  694. $error.fadeIn(800);
  695. self.raise('fileerror', [params]);
  696. self.clearFileInput();
  697. addCss(self.$container, 'has-error');
  698. },
  699. setProgress: function (p) {
  700. var self = this, pct = Math.min(p, 100),
  701. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  702. if (!isEmpty(template)) {
  703. self.$progress.html(template.repl('{percent}', pct));
  704. }
  705. },
  706. upload: function () {
  707. var self = this, totLen = self.getFileStack().length, params = {},
  708. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  709. if (totLen < self.minFileCount && self.minFileCount > 0) {
  710. self.noFilesError(params);
  711. return;
  712. }
  713. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  714. return;
  715. }
  716. self.resetUpload();
  717. self.$progress.removeClass('hide');
  718. self.uploadCount = 0;
  719. self.uploadPercent = 0;
  720. self.lock();
  721. self.setProgress(0);
  722. if (totLen === 0 && hasExtraData) {
  723. self.uploadExtraOnly();
  724. return;
  725. }
  726. len = self.filestack.length;
  727. self.hasInitData = false;
  728. if (self.uploadAsync && self.showPreview) {
  729. outData = self.getOutData();
  730. self.raise('filebatchpreupload', [outData]);
  731. self.fileBatchCompleted = false;
  732. self.uploadCache = {content: [], config: [], tags: [], append: true};
  733. for (i = 0; i < len; i += 1) {
  734. if (self.filestack[i] !== undefined) {
  735. self.uploadSingle(i, self.filestack, true);
  736. }
  737. }
  738. return;
  739. }
  740. self.uploadBatch();
  741. },
  742. lock: function () {
  743. var self = this;
  744. self.resetErrors();
  745. self.disable();
  746. if (self.showRemove) {
  747. addCss(self.$container.find('.fileinput-remove'), 'hide');
  748. }
  749. if (self.showCancel) {
  750. self.$container.find('.fileinput-cancel').removeClass('hide');
  751. }
  752. self.raise('filelock', [self.filestack, self.getExtraData()]);
  753. },
  754. unlock: function (reset) {
  755. var self = this;
  756. if (reset === undefined) {
  757. reset = true;
  758. }
  759. self.enable();
  760. if (self.showCancel) {
  761. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  762. }
  763. if (self.showRemove) {
  764. self.$container.find('.fileinput-remove').removeClass('hide');
  765. }
  766. if (reset) {
  767. self.resetFileStack();
  768. }
  769. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  770. },
  771. resetFileStack: function () {
  772. var self = this, i = 0, newstack = [];
  773. self.getThumbs().each(function () {
  774. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  775. file = self.filestack[ind];
  776. if (ind === -1) {
  777. return;
  778. }
  779. if (file !== undefined) {
  780. newstack[i] = file;
  781. $thumb.attr({
  782. 'id': self.previewInitId + '-' + i,
  783. 'data-fileindex': i
  784. });
  785. i += 1;
  786. } else {
  787. $thumb.attr({
  788. 'id': 'uploaded-' + uniqId(),
  789. 'data-fileindex': '-1'
  790. });
  791. }
  792. });
  793. self.filestack = newstack;
  794. },
  795. destroy: function () {
  796. var self = this, $cont = self.$container;
  797. $cont.find('.file-drop-zone').off();
  798. self.$element.insertBefore($cont).off('.fileinput').removeData();
  799. $cont.off().remove();
  800. },
  801. refresh: function (options) {
  802. var self = this, $el = self.$element;
  803. options = options ? $.extend(self.options, options) : self.options;
  804. self.destroy();
  805. $el.fileinput(options);
  806. if ($el.val()) {
  807. $el.trigger('change.fileinput');
  808. }
  809. },
  810. initDragDrop: function () {
  811. var self = this, $zone = self.$container.find('.file-drop-zone'),
  812. allEvents = 'dragenter.fileinput dragover.fileinput drop.fileinput';
  813. handler($zone, 'dragenter.fileinput dragover.fileinput', function (e) {
  814. var hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  815. e.stopPropagation();
  816. e.preventDefault();
  817. if (self.isDisabled || !hasFiles) {
  818. e.originalEvent.dataTransfer.effectAllowed = 'none';
  819. e.originalEvent.dataTransfer.dropEffect = 'none';
  820. return;
  821. }
  822. addCss($(this), 'highlighted');
  823. }, true);
  824. handler($zone, 'dragleave', function (e) {
  825. e.stopPropagation();
  826. e.preventDefault();
  827. if (self.isDisabled) {
  828. return;
  829. }
  830. $(this).removeClass('highlighted');
  831. });
  832. handler($zone, 'drop', function (e) {
  833. e.preventDefault();
  834. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  835. return;
  836. }
  837. self.change(e, 'dragdrop');
  838. $(this).removeClass('highlighted');
  839. });
  840. handler($(document), allEvents, function (e) {
  841. e.stopPropagation();
  842. e.preventDefault();
  843. }, true);
  844. },
  845. setFileDropZoneTitle: function () {
  846. var self = this, $zone = self.$container.find('.file-drop-zone');
  847. $zone.find('.' + self.dropZoneTitleClass).remove();
  848. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  849. return;
  850. }
  851. if ($zone.find('.file-preview-frame').length === 0) {
  852. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  853. }
  854. self.$container.removeClass('file-input-new');
  855. addCss(self.$container, 'file-input-ajax-new');
  856. },
  857. initFileActions: function () {
  858. var self = this;
  859. self.$preview.find('.kv-file-remove').each(function () {
  860. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  861. ind = $frame.attr('data-fileindex'), n, cap;
  862. handler($el, 'click', function () {
  863. self.cleanMemory($frame);
  864. $frame.fadeOut('slow', function () {
  865. self.filestack[ind] = undefined;
  866. self.clearObjects($frame);
  867. $frame.remove();
  868. var filestack = self.getFileStack(true), len = filestack.length,
  869. chk = previewCache.count(self.id);
  870. self.clearFileInput();
  871. if (len === 0 && chk === 0) {
  872. self.reset();
  873. } else {
  874. n = chk + len;
  875. cap = n > 1 ? self.getMsgSelected(n) : (filestack[0] ? filestack[0].name : '');
  876. self.setCaption(cap);
  877. }
  878. });
  879. });
  880. });
  881. self.$preview.find('.kv-file-upload').each(function () {
  882. var $el = $(this);
  883. handler($el, 'click', function () {
  884. var $frame = $el.closest('.file-preview-frame'),
  885. ind = $frame.attr('data-fileindex');
  886. self.uploadSingle(ind, self.filestack, false);
  887. });
  888. });
  889. },
  890. getMsgSelected: function (n) {
  891. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  892. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  893. },
  894. renderFileFooter: function (caption, width) {
  895. var self = this, config = self.fileActionSettings, footer, out,
  896. template = self.getLayoutTemplate('footer');
  897. if (self.isUploadable) {
  898. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false));
  899. out = footer.repl('{caption}', caption)
  900. .repl('{width}', width)
  901. .repl('{indicator}', config.indicatorNew)
  902. .repl('{indicatorTitle}', config.indicatorNewTitle);
  903. } else {
  904. out = template.repl('{actions}', '')
  905. .repl('{caption}', caption)
  906. .repl('{width}', width)
  907. .repl('{indicator}', '')
  908. .repl('{indicatorTitle}', '');
  909. }
  910. out = replaceTags(out, self.previewThumbTags);
  911. return out;
  912. },
  913. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  914. if (!showUpload && !showDelete) {
  915. return '';
  916. }
  917. var self = this,
  918. vUrl = url === false ? '' : ' data-url="' + url + '"',
  919. vKey = key === false ? '' : ' data-key="' + key + '"',
  920. btnDelete = self.getLayoutTemplate('actionDelete'),
  921. btnUpload = '',
  922. template = self.getLayoutTemplate('actions'),
  923. otherButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  924. config = self.fileActionSettings,
  925. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  926. btnDelete = btnDelete
  927. .repl('{removeClass}', removeClass)
  928. .repl('{removeIcon}', config.removeIcon)
  929. .repl('{removeTitle}', config.removeTitle)
  930. .repl('{dataUrl}', vUrl)
  931. .repl('{dataKey}', vKey);
  932. if (showUpload) {
  933. btnUpload = self.getLayoutTemplate('actionUpload')
  934. .repl('{uploadClass}', config.uploadClass)
  935. .repl('{uploadIcon}', config.uploadIcon)
  936. .repl('{uploadTitle}', config.uploadTitle);
  937. }
  938. return template
  939. .repl('{delete}', btnDelete)
  940. .repl('{upload}', btnUpload)
  941. .repl('{other}', otherButtons);
  942. },
  943. setThumbStatus: function ($thumb, status) {
  944. var self = this, icon = 'indicator' + status, msg = icon + 'Title',
  945. css = 'file-preview-' + status.toLowerCase(),
  946. $indicator = $thumb.find('.file-upload-indicator'),
  947. config = self.fileActionSettings;
  948. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  949. $indicator.html(config[icon]);
  950. $indicator.attr('title', config[msg]);
  951. $thumb.addClass(css);
  952. },
  953. clearPreview: function () {
  954. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  955. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  956. $thumbs.remove();
  957. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  958. self.resetUpload();
  959. }
  960. },
  961. initPreview: function (isInit) {
  962. var self = this, cap = self.initialCaption || '', out;
  963. if (!previewCache.count(self.id)) {
  964. self.clearPreview();
  965. if (isInit) {
  966. self.setCaption(cap);
  967. } else {
  968. self.initCaption();
  969. }
  970. return;
  971. }
  972. out = previewCache.out(self.id);
  973. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  974. self.$preview.html(out.content);
  975. self.setCaption(cap);
  976. if (!isEmpty(out.content)) {
  977. self.$container.removeClass('file-input-new');
  978. }
  979. },
  980. initPreviewDeletes: function () {
  981. var self = this, deleteExtraData = self.deleteExtraData || {},
  982. resetProgress = function () {
  983. if (self.$preview.find('.kv-file-remove').length === 0) {
  984. self.reset();
  985. self.initialCaption = '';
  986. }
  987. };
  988. self.$preview.find('.kv-file-remove').each(function () {
  989. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  990. if (isEmpty(vUrl) || vKey === undefined) {
  991. return;
  992. }
  993. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  994. settings, params, index = $frame.data('fileindex'), config, extraData;
  995. index = parseInt(index.replace('init_', ''));
  996. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  997. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  998. if (typeof extraData === "function") {
  999. extraData = extraData();
  1000. }
  1001. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1002. settings = $.extend({
  1003. url: vUrl,
  1004. type: 'DELETE',
  1005. dataType: 'json',
  1006. data: $.extend({key: vKey}, extraData),
  1007. beforeSend: function (jqXHR) {
  1008. self.ajaxAborted = false;
  1009. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  1010. if (self.ajaxAborted) {
  1011. jqXHR.abort();
  1012. } else {
  1013. addCss($frame, 'file-uploading');
  1014. addCss($el, 'disabled');
  1015. }
  1016. },
  1017. success: function (data, textStatus, jqXHR) {
  1018. var n, cap;
  1019. if (isEmpty(data) || isEmpty(data.error)) {
  1020. previewCache.unset(self.id, index);
  1021. n = previewCache.count(self.id);
  1022. cap = n > 0 ? self.getMsgSelected(n) : '';
  1023. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  1024. self.setCaption(cap);
  1025. } else {
  1026. params.jqXHR = jqXHR;
  1027. params.response = data;
  1028. self.showError(data.error, params, 'filedeleteerror');
  1029. $frame.removeClass('file-uploading');
  1030. $el.removeClass('disabled');
  1031. resetProgress();
  1032. return;
  1033. }
  1034. $frame.removeClass('file-uploading').addClass('file-deleted');
  1035. $frame.fadeOut('slow', function () {
  1036. self.clearObjects($frame);
  1037. $frame.remove();
  1038. resetProgress();
  1039. if (!n && self.getFileStack().length === 0) {
  1040. self.setCaption('');
  1041. self.reset();
  1042. }
  1043. });
  1044. },
  1045. error: function (jqXHR, textStatus, errorThrown) {
  1046. var errMsg = self.parseError(jqXHR, errorThrown);
  1047. params.jqXHR = jqXHR;
  1048. params.response = {};
  1049. self.showError(errMsg, params, 'filedeleteerror');
  1050. $frame.removeClass('file-uploading');
  1051. resetProgress();
  1052. }
  1053. }, self.ajaxDeleteSettings);
  1054. handler($el, 'click', function () {
  1055. $.ajax(settings);
  1056. });
  1057. });
  1058. },
  1059. clearObjects: function ($el) {
  1060. $el.find('video audio').each(function () {
  1061. this.pause();
  1062. $(this).remove();
  1063. });
  1064. $el.find('img object div').each(function () {
  1065. $(this).remove();
  1066. });
  1067. },
  1068. clearFileInput: function () {
  1069. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1070. if (isEmpty($el.val())) {
  1071. return;
  1072. }
  1073. // Fix for IE ver < 11, that does not clear file inputs
  1074. // Requires a sequence of steps to prevent IE crashing but
  1075. // still allow clearing of the file input.
  1076. if (self.isIE9 || self.isIE10) {
  1077. $srcFrm = $el.closest('form');
  1078. $tmpFrm = $(document.createElement('form'));
  1079. $tmpEl = $(document.createElement('div'));
  1080. $el.before($tmpEl);
  1081. if ($srcFrm.length) {
  1082. $srcFrm.after($tmpFrm);
  1083. } else {
  1084. $tmpEl.after($tmpFrm);
  1085. }
  1086. $tmpFrm.append($el).trigger('reset');
  1087. $tmpEl.before($el).remove();
  1088. $tmpFrm.remove();
  1089. } else { // normal input clear behavior for other sane browsers
  1090. $el.val('');
  1091. }
  1092. self.fileInputCleared = true;
  1093. },
  1094. resetUpload: function () {
  1095. var self = this;
  1096. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1097. self.uploadCount = 0;
  1098. self.uploadPercent = 0;
  1099. self.$btnUpload.removeAttr('disabled');
  1100. self.setProgress(0);
  1101. addCss(self.$progress, 'hide');
  1102. self.resetErrors(false);
  1103. self.ajaxAborted = false;
  1104. self.ajaxRequests = [];
  1105. },
  1106. cancel: function () {
  1107. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1108. if (len > 0) {
  1109. for (i = 0; i < len; i += 1) {
  1110. xhr[i].abort();
  1111. }
  1112. }
  1113. self.getThumbs().each(function () {
  1114. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1115. $thumb.removeClass('file-uploading');
  1116. if (self.filestack[ind] !== undefined) {
  1117. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1118. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1119. }
  1120. self.unlock();
  1121. });
  1122. },
  1123. cleanMemory: function ($thumb) {
  1124. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  1125. objUrl.revokeObjectURL(data);
  1126. },
  1127. hasInitialPreview: function () {
  1128. var self = this;
  1129. return !self.overwriteInitial && previewCache.count(self.id);
  1130. },
  1131. clear: function () {
  1132. var self = this, cap;
  1133. self.$btnUpload.removeAttr('disabled');
  1134. self.getThumbs().find('video,audio,img').each(function () {
  1135. self.cleanMemory($(this));
  1136. });
  1137. self.resetUpload();
  1138. self.filestack = [];
  1139. self.clearFileInput();
  1140. self.resetErrors(true);
  1141. self.raise('fileclear');
  1142. if (self.hasInitialPreview()) {
  1143. self.showFileIcon();
  1144. self.resetPreview();
  1145. self.setEllipsis();
  1146. self.initPreviewDeletes();
  1147. self.$container.removeClass('file-input-new');
  1148. } else {
  1149. self.getThumbs().each(function () {
  1150. self.clearObjects($(this));
  1151. });
  1152. if (self.isUploadable) {
  1153. previewCache.data[self.id] = {};
  1154. }
  1155. self.$preview.html('');
  1156. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1157. self.setCaption(cap);
  1158. self.setEllipsis();
  1159. self.$caption.attr('title', '');
  1160. addCss(self.$container, 'file-input-new');
  1161. }
  1162. if (self.$container.find('.file-preview-frame').length === 0) {
  1163. if (!self.initCaption()) {
  1164. self.$captionContainer.find('.kv-caption-icon').hide();
  1165. }
  1166. self.setEllipsis();
  1167. }
  1168. self.hideFileIcon();
  1169. self.raise('filecleared');
  1170. self.$captionContainer.focus();
  1171. self.setFileDropZoneTitle();
  1172. },
  1173. resetPreview: function () {
  1174. var self = this, out;
  1175. if (previewCache.count(self.id)) {
  1176. out = previewCache.out(self.id);
  1177. self.$preview.html(out.content);
  1178. self.setCaption(out.caption);
  1179. } else {
  1180. self.clearPreview();
  1181. self.initCaption();
  1182. }
  1183. },
  1184. reset: function () {
  1185. var self = this;
  1186. self.resetPreview();
  1187. self.setEllipsis();
  1188. self.$container.find('.fileinput-filename').text('');
  1189. self.raise('filereset');
  1190. addCss(self.$container, 'file-input-new');
  1191. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  1192. self.$container.removeClass('file-input-new');
  1193. }
  1194. self.setFileDropZoneTitle();
  1195. self.filestack = [];
  1196. self.formdata = {};
  1197. },
  1198. disable: function () {
  1199. var self = this;
  1200. self.isDisabled = true;
  1201. self.raise('filedisabled');
  1202. self.$element.attr('disabled', 'disabled');
  1203. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1204. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload, .file-preview-frame button").attr("disabled", true);
  1205. self.initDragDrop();
  1206. },
  1207. enable: function () {
  1208. var self = this;
  1209. self.isDisabled = false;
  1210. self.raise('fileenabled');
  1211. self.$element.removeAttr('disabled');
  1212. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1213. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  1214. self.initDragDrop();
  1215. },
  1216. getThumbs: function (css) {
  1217. css = css || '';
  1218. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1219. },
  1220. getExtraData: function (previewId, index) {
  1221. var self = this, data = self.uploadExtraData;
  1222. if (typeof self.uploadExtraData === "function") {
  1223. data = self.uploadExtraData(previewId, index);
  1224. }
  1225. return data;
  1226. },
  1227. uploadExtra: function (previewId, index) {
  1228. var self = this, data = self.getExtraData(previewId, index);
  1229. if (data.length === 0) {
  1230. return;
  1231. }
  1232. $.each(data, function (key, value) {
  1233. self.formdata.append(key, value);
  1234. });
  1235. },
  1236. initXhr: function (xhrobj, factor) {
  1237. var self = this;
  1238. if (xhrobj.upload) {
  1239. xhrobj.upload.addEventListener('progress', function (event) {
  1240. var pct = 0, position = event.loaded || event.position, total = event.total;
  1241. if (event.lengthComputable) {
  1242. pct = Math.ceil(position / total * factor);
  1243. }
  1244. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1245. self.setProgress(self.uploadPercent);
  1246. }, false);
  1247. }
  1248. return xhrobj;
  1249. },
  1250. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1251. var self = this, settings;
  1252. settings = $.extend({
  1253. xhr: function () {
  1254. var xhrobj = $.ajaxSettings.xhr();
  1255. return self.initXhr(xhrobj, 98);
  1256. },
  1257. url: self.uploadUrl,
  1258. type: 'POST',
  1259. dataType: 'json',
  1260. data: self.formdata,
  1261. cache: false,
  1262. processData: false,
  1263. contentType: false,
  1264. beforeSend: function () {
  1265. fnBefore.apply(this, arguments);
  1266. self.uploadExtra(previewId, index);
  1267. },
  1268. success: fnSuccess,
  1269. complete: fnComplete,
  1270. error: fnError
  1271. }, self.ajaxSettings);
  1272. self.ajaxRequests.push($.ajax(settings));
  1273. },
  1274. initUploadSuccess: function (out, $thumb, allFiles) {
  1275. var self = this, append, data, index, $newThumb, content, config, tags;
  1276. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1277. return;
  1278. }
  1279. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1280. self.hasInitData = true;
  1281. content = out.initialPreview || [];
  1282. config = out.initialPreviewConfig || [];
  1283. tags = out.initialPreviewThumbTags || [];
  1284. append = out.append === undefined || out.append ? true : false;
  1285. self.overwriteInitial = false;
  1286. if ($thumb !== undefined && !allFiles) {
  1287. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1288. data = previewCache.get(self.id, index, false);
  1289. $newThumb = $(data).hide();
  1290. $thumb.after($newThumb).fadeOut('slow', function () {
  1291. $newThumb.fadeIn('slow').css('display:inline-block');
  1292. self.initPreviewDeletes();
  1293. self.clearFileInput();
  1294. $thumb.remove();
  1295. });
  1296. } else {
  1297. if (allFiles) {
  1298. self.uploadCache.content.push(content[0]);
  1299. self.uploadCache.config.push(config[0]);
  1300. self.uploadCache.tags.push(tags[0]);
  1301. self.uploadCache.append = append;
  1302. } else {
  1303. previewCache.set(self.id, content, config, tags, append);
  1304. self.initPreview();
  1305. self.initPreviewDeletes();
  1306. }
  1307. }
  1308. }
  1309. },
  1310. initSuccessThumbs: function () {
  1311. var self = this;
  1312. self.getThumbs('.file-preview-success').each(function () {
  1313. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1314. $remove.removeAttr('disabled');
  1315. handler($remove, 'click', function () {
  1316. var out = self.raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1317. self.cleanMemory($thumb);
  1318. if (out === false) {
  1319. return;
  1320. }
  1321. $thumb.fadeOut('slow', function () {
  1322. $thumb.remove();
  1323. if (!self.$preview.find('.file-preview-frame').length) {
  1324. self.reset();
  1325. }
  1326. });
  1327. });
  1328. });
  1329. },
  1330. uploadSingle: function (i, files, allFiles) {
  1331. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1332. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1333. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1334. updateProgress, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1335. resetActions, fnBefore, fnSuccess, fnComplete, fnError, params = {id: previewId, index: i};
  1336. self.formdata = formdata;
  1337. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1338. return;
  1339. }
  1340. chkComplete = function () {
  1341. var $thumbs = self.getThumbs('.file-uploading');
  1342. if ($thumbs.length > 0 || self.fileBatchCompleted) {
  1343. return;
  1344. }
  1345. self.fileBatchCompleted = true;
  1346. setTimeout(function () {
  1347. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.tags,
  1348. self.uploadCache.append);
  1349. if (self.hasInitData) {
  1350. self.initPreview();
  1351. self.initPreviewDeletes();
  1352. }
  1353. self.setProgress(100);
  1354. self.unlock();
  1355. self.clearFileInput();
  1356. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1357. }, 100);
  1358. };
  1359. updateProgress = function () {
  1360. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1361. return;
  1362. }
  1363. self.uploadCount += 1;
  1364. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1365. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1366. self.setProgress(self.uploadPercent);
  1367. self.initPreviewDeletes();
  1368. };
  1369. resetActions = function () {
  1370. $btnUpload.removeAttr('disabled');
  1371. $btnDelete.removeAttr('disabled');
  1372. $thumb.removeClass('file-uploading');
  1373. };
  1374. fnBefore = function (jqXHR) {
  1375. outData = self.getOutData(jqXHR);
  1376. if (!$thumb.hasClass('file-preview-success')) {
  1377. self.setThumbStatus($thumb, 'Loading');
  1378. addCss($thumb, 'file-uploading');
  1379. }
  1380. $btnUpload.attr('disabled', true);
  1381. $btnDelete.attr('disabled', true);
  1382. if (!allFiles) {
  1383. self.lock();
  1384. }
  1385. self.raise('filepreupload', [outData, previewId, i]);
  1386. params = $.extend(params, outData);
  1387. if (self.abort(params)) {
  1388. jqXHR.abort();
  1389. self.setProgress(100);
  1390. }
  1391. };
  1392. fnSuccess = function (data, textStatus, jqXHR) {
  1393. outData = self.getOutData(jqXHR, data);
  1394. params = $.extend(params, outData);
  1395. setTimeout(function () {
  1396. if (isEmpty(data) || isEmpty(data.error)) {
  1397. self.setThumbStatus($thumb, 'Success');
  1398. $btnUpload.hide();
  1399. self.filestack[i] = undefined;
  1400. self.raise('fileuploaded', [outData, previewId, i]);
  1401. self.initUploadSuccess(data, $thumb, allFiles);
  1402. if (!allFiles) {
  1403. self.resetFileStack();
  1404. }
  1405. } else {
  1406. self.setThumbStatus($thumb, 'Error');
  1407. self.showUploadError(data.error, params);
  1408. }
  1409. }, 100);
  1410. };
  1411. fnComplete = function () {
  1412. setTimeout(function () {
  1413. updateProgress();
  1414. resetActions();
  1415. if (!allFiles) {
  1416. self.unlock(false);
  1417. } else {
  1418. chkComplete();
  1419. }
  1420. self.initSuccessThumbs();
  1421. }, 100);
  1422. };
  1423. fnError = function (jqXHR, textStatus, errorThrown) {
  1424. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1425. self.setThumbStatus($thumb, 'Error');
  1426. params = $.extend(params, self.getOutData(jqXHR));
  1427. self.showUploadError(errMsg, params);
  1428. };
  1429. formdata.append(self.uploadFileAttr, files[i]);
  1430. formdata.append('file_id', i);
  1431. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1432. },
  1433. uploadBatch: function () {
  1434. var self = this, files = self.filestack, total = files.length, config,
  1435. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1436. setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1437. params = {};
  1438. self.formdata = new FormData();
  1439. if (total === 0 || !hasPostData || self.abort(params)) {
  1440. return;
  1441. }
  1442. setAllUploaded = function () {
  1443. $.each(files, function (key) {
  1444. self.filestack[key] = undefined;
  1445. });
  1446. self.clearFileInput();
  1447. };
  1448. fnBefore = function (jqXHR) {
  1449. self.lock();
  1450. var outData = self.getOutData(jqXHR);
  1451. if (self.showPreview) {
  1452. self.getThumbs().each(function () {
  1453. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1454. $btnDelete = $thumb.find('.kv-file-remove');
  1455. if (!$thumb.hasClass('file-preview-success')) {
  1456. self.setThumbStatus($thumb, 'Loading');
  1457. addCss($thumb, 'file-uploading');
  1458. }
  1459. $btnUpload.attr('disabled', true);
  1460. $btnDelete.attr('disabled', true);
  1461. });
  1462. }
  1463. self.raise('filebatchpreupload', [outData]);
  1464. if (self.abort(outData)) {
  1465. jqXHR.abort();
  1466. }
  1467. };
  1468. fnSuccess = function (data, textStatus, jqXHR) {
  1469. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(),
  1470. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys, key = 0;
  1471. if (isEmpty(data) || isEmpty(data.error)) {
  1472. self.raise('filebatchuploadsuccess', [outData]);
  1473. setAllUploaded();
  1474. if (self.showPreview) {
  1475. $thumbs.each(function () {
  1476. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1477. $thumb.find('.kv-file-upload').hide();
  1478. self.setThumbStatus($thumb, 'Success');
  1479. $thumb.removeClass('file-uploading');
  1480. $btnUpload.removeAttr('disabled');
  1481. });
  1482. self.initUploadSuccess(data);
  1483. } else {
  1484. self.reset();
  1485. }
  1486. } else {
  1487. if (self.showPreview) {
  1488. $thumbs.each(function () {
  1489. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1490. $btnUpload = $thumb.find('.kv-file-upload');
  1491. $thumb.removeClass('file-uploading');
  1492. $btnUpload.removeAttr('disabled');
  1493. $btnDelete.removeAttr('disabled');
  1494. if (keys.length === 0) {
  1495. self.setThumbStatus($thumb, 'Error');
  1496. return;
  1497. }
  1498. if ($.inArray(key, keys) !== -1) {
  1499. self.setThumbStatus($thumb, 'Error');
  1500. } else {
  1501. $thumb.find('.kv-file-upload').hide();
  1502. self.setThumbStatus($thumb, 'Success');
  1503. self.filestack[key] = undefined;
  1504. }
  1505. key++;
  1506. });
  1507. self.initUploadSuccess(data);
  1508. }
  1509. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1510. }
  1511. };
  1512. fnComplete = function () {
  1513. self.setProgress(100);
  1514. self.unlock();
  1515. self.initSuccessThumbs();
  1516. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1517. self.clearFileInput();
  1518. };
  1519. fnError = function (jqXHR, textStatus, errorThrown) {
  1520. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1521. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1522. self.uploadFileCount = total - 1;
  1523. if (!self.showPreview) {
  1524. return;
  1525. }
  1526. self.getThumbs().each(function () {
  1527. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1528. $thumb.removeClass('file-uploading');
  1529. if (self.filestack[key] !== undefined) {
  1530. self.setThumbStatus($thumb, 'Error');
  1531. }
  1532. });
  1533. self.getThumbs().removeClass('file-uploading');
  1534. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1535. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1536. };
  1537. $.each(files, function (key, data) {
  1538. if (!isEmpty(files[key])) {
  1539. self.formdata.append(self.uploadFileAttr, data);
  1540. }
  1541. });
  1542. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1543. },
  1544. uploadExtraOnly: function () {
  1545. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1546. self.formdata = new FormData();
  1547. if (self.abort(params)) {
  1548. return;
  1549. }
  1550. fnBefore = function (jqXHR) {
  1551. self.lock();
  1552. var outData = self.getOutData(jqXHR);
  1553. self.raise('filebatchpreupload', [outData]);
  1554. self.setProgress(50);
  1555. params.data = outData;
  1556. params.xhr = jqXHR;
  1557. if (self.abort(params)) {
  1558. jqXHR.abort();
  1559. self.setProgress(100);
  1560. }
  1561. };
  1562. fnSuccess = function (data, textStatus, jqXHR) {
  1563. var outData = self.getOutData(jqXHR, data);
  1564. if (isEmpty(data) || isEmpty(data.error)) {
  1565. self.raise('filebatchuploadsuccess', [outData]);
  1566. self.clearFileInput();
  1567. self.initUploadSuccess(data);
  1568. } else {
  1569. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1570. }
  1571. };
  1572. fnComplete = function () {
  1573. self.setProgress(100);
  1574. self.unlock();
  1575. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1576. self.clearFileInput();
  1577. };
  1578. fnError = function (jqXHR, textStatus, errorThrown) {
  1579. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1580. params.data = outData;
  1581. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1582. };
  1583. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1584. },
  1585. hideFileIcon: function () {
  1586. if (this.overwriteInitial) {
  1587. this.$captionContainer.find('.kv-caption-icon').hide();
  1588. }
  1589. },
  1590. showFileIcon: function () {
  1591. this.$captionContainer.find('.kv-caption-icon').show();
  1592. },
  1593. resetErrors: function (fade) {
  1594. var self = this, $error = self.$errorContainer;
  1595. self.isError = false;
  1596. self.$container.removeClass('has-error');
  1597. $error.html('');
  1598. if (fade) {
  1599. $error.fadeOut('slow');
  1600. } else {
  1601. $error.hide();
  1602. }
  1603. },
  1604. showFolderError: function (folders) {
  1605. var self = this, $error = self.$errorContainer;
  1606. if (!folders) {
  1607. return;
  1608. }
  1609. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1610. $error.fadeIn(800);
  1611. addCss(self.$container, 'has-error');
  1612. self.raise('filefoldererror', [folders]);
  1613. },
  1614. showUploadError: function (msg, params, event) {
  1615. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1616. if ($error.find('ul').length === 0) {
  1617. $error.html('<ul><li>' + msg + '</li></ul>');
  1618. } else {
  1619. $error.find('ul').append('<li>' + msg + '</li>');
  1620. }
  1621. $error.fadeIn(800);
  1622. self.raise(ev, [params]);
  1623. self.$container.removeClass('file-input-new');
  1624. addCss(self.$container, 'has-error');
  1625. return true;
  1626. },
  1627. showError: function (msg, params, event) {
  1628. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1629. params = params || {};
  1630. params.reader = self.reader;
  1631. $error.html(msg);
  1632. $error.fadeIn(800);
  1633. self.raise(ev, [params]);
  1634. if (!self.isUploadable) {
  1635. self.clearFileInput();
  1636. }
  1637. self.$container.removeClass('file-input-new');
  1638. addCss(self.$container, 'has-error');
  1639. self.$btnUpload.attr('disabled', true);
  1640. return true;
  1641. },
  1642. errorHandler: function (evt, caption) {
  1643. var self = this, err = evt.target.error;
  1644. switch (err.code) {
  1645. case err.NOT_FOUND_ERR:
  1646. self.showError(self.msgFileNotFound.replace('{name}', caption));
  1647. break;
  1648. case err.SECURITY_ERR:
  1649. self.showError(self.msgFileSecured.replace('{name}', caption));
  1650. break;
  1651. case err.NOT_READABLE_ERR:
  1652. self.showError(self.msgFileNotReadable.replace('{name}', caption));
  1653. break;
  1654. case err.ABORT_ERR:
  1655. self.showError(self.msgFilePreviewAborted.replace('{name}', caption));
  1656. break;
  1657. default:
  1658. self.showError(self.msgFilePreviewError.replace('{name}', caption));
  1659. }
  1660. },
  1661. parseFileType: function (file) {
  1662. var self = this, isValid, vType, cat, i;
  1663. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1664. cat = defaultPreviewTypes[i];
  1665. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1666. vType = isValid(file.type, file.name) ? cat : '';
  1667. if (!isEmpty(vType)) {
  1668. return vType;
  1669. }
  1670. }
  1671. return 'other';
  1672. },
  1673. previewDefault: function (file, previewId, isDisabled) {
  1674. if (!this.showPreview) {
  1675. return;
  1676. }
  1677. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1678. config = self.previewSettings.other || defaultPreviewSettings.other,
  1679. footer = self.renderFileFooter(file.name, config.width),
  1680. previewOtherTemplate = self.getPreviewTemplate('other'),
  1681. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1682. frameClass = '';
  1683. if (isDisabled === true) {
  1684. frameClass = ' btn disabled';
  1685. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1686. }
  1687. self.$preview.append("\n" + previewOtherTemplate
  1688. .repl('{previewId}', previewId)
  1689. .repl('{frameClass}', frameClass)
  1690. .repl('{fileindex}', ind)
  1691. .repl('{caption}', self.slug(file.name))
  1692. .repl('{width}', config.width)
  1693. .repl('{height}', config.height)
  1694. .repl('{type}', file.type)
  1695. .repl('{data}', data)
  1696. .repl('{footer}', footer));
  1697. },
  1698. previewFile: function (i, file, theFile, previewId, data) {
  1699. if (!this.showPreview) {
  1700. return;
  1701. }
  1702. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1703. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1704. tmplt = self.getPreviewTemplate(cat),
  1705. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1706. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1707. chkTypes = types.indexOf(cat) >= 0, id, height,
  1708. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && mimes.indexOf(file.type) !== -1),
  1709. footer = self.renderFileFooter(caption, config.width), modal = '',
  1710. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1711. if (chkTypes && chkMimes) {
  1712. if (cat === 'text') {
  1713. strText = htmlEncode(theFile.target.result);
  1714. if (strText.length > wrapLen) {
  1715. id = 'text-' + uniqId();
  1716. height = window.innerHeight * 0.75;
  1717. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1718. .repl('{title}', caption)
  1719. .repl('{height}', height)
  1720. .repl('{body}', strText);
  1721. wrapInd = wrapInd
  1722. .repl('{title}', caption)
  1723. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1724. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1725. }
  1726. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1727. .repl('{frameClass}', '')
  1728. .repl('{type}', file.type).repl('{width}', config.width)
  1729. .repl('{height}', config.height).repl('{data}', strText)
  1730. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1731. } else {
  1732. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1733. .repl('{frameClass}', '')
  1734. .repl('{type}', file.type).repl('{data}', data)
  1735. .repl('{width}', config.width).repl('{height}', config.height)
  1736. .repl('{footer}', footer).repl('{fileindex}', ind);
  1737. }
  1738. self.$preview.append("\n" + content);
  1739. self.validateImage(i, previewId);
  1740. } else {
  1741. self.previewDefault(file, previewId);
  1742. }
  1743. },
  1744. slugDefault: function (text) {
  1745. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1746. },
  1747. getFileStack: function (skipNull) {
  1748. var self = this, status;
  1749. return self.filestack.filter(function (n) {
  1750. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  1751. });
  1752. },
  1753. readFiles: function (files) {
  1754. this.reader = new FileReader();
  1755. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1756. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1757. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1758. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1759. throwError = function (msg, file, previewId, index) {
  1760. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1761. p2 = {id: previewId, index: index, file: file, files: files};
  1762. self.previewDefault(file, previewId, true);
  1763. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1764. };
  1765. function readFile(i) {
  1766. if (isEmpty($el.attr('multiple'))) {
  1767. numFiles = 1;
  1768. }
  1769. if (i >= numFiles) {
  1770. if (self.isUploadable && self.filestack.length > 0) {
  1771. self.raise('filebatchselected', [self.getFileStack()]);
  1772. } else {
  1773. self.raise('filebatchselected', [files]);
  1774. }
  1775. $container.removeClass('loading');
  1776. $status.html('');
  1777. return;
  1778. }
  1779. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1780. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1781. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1782. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1783. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1784. if (!isEmpty(fileExt)) {
  1785. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1786. }
  1787. fileSize = fileSize.toFixed(2);
  1788. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1789. msg = self.msgSizeTooLarge.replace('{name}', caption)
  1790. .replace('{size}', fileSize)
  1791. .replace('{maxSize}', self.maxFileSize);
  1792. self.isError = throwError(msg, file, previewId, i);
  1793. return;
  1794. }
  1795. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1796. for (j = 0; j < fileTypes.length; j += 1) {
  1797. typ = fileTypes[j];
  1798. checkFile = settings[typ];
  1799. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1800. fileCount += isEmpty(chk) ? 0 : chk.length;
  1801. }
  1802. if (fileCount === 0) {
  1803. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  1804. self.isError = throwError(msg, file, previewId, i);
  1805. return;
  1806. }
  1807. }
  1808. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1809. chk = caption.match(fileExtExpr);
  1810. fileCount += isEmpty(chk) ? 0 : chk.length;
  1811. if (fileCount === 0) {
  1812. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  1813. strExt);
  1814. self.isError = throwError(msg, file, previewId, i);
  1815. return;
  1816. }
  1817. }
  1818. if (!self.showPreview) {
  1819. self.filestack.push(file);
  1820. setTimeout(readFile(i + 1), 100);
  1821. self.raise('fileloaded', [file, previewId, i, reader]);
  1822. return;
  1823. }
  1824. if ($preview.length > 0 && FileReader !== undefined) {
  1825. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  1826. $container.addClass('loading');
  1827. reader.onerror = function (evt) {
  1828. self.errorHandler(evt, caption);
  1829. };
  1830. reader.onload = function (theFile) {
  1831. self.previewFile(i, file, theFile, previewId, previewData);
  1832. self.initFileActions();
  1833. };
  1834. reader.onloadend = function () {
  1835. msg = msgProgress
  1836. .replace('{index}', i + 1).replace('{files}', numFiles)
  1837. .replace('{percent}', 50).replace('{name}', caption);
  1838. setTimeout(function () {
  1839. $status.html(msg);
  1840. self.updateFileDetails(numFiles);
  1841. readFile(i + 1);
  1842. }, 100);
  1843. self.raise('fileloaded', [file, previewId, i, reader]);
  1844. };
  1845. reader.onprogress = function (data) {
  1846. if (data.lengthComputable) {
  1847. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1848. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  1849. .replace('{percent}', progress).replace('{name}', caption);
  1850. setTimeout(function () {
  1851. $status.html(msg);
  1852. }, 100);
  1853. }
  1854. };
  1855. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1856. if (isText(file.type, caption)) {
  1857. reader.readAsText(file, self.textEncoding);
  1858. } else {
  1859. reader.readAsArrayBuffer(file);
  1860. }
  1861. } else {
  1862. self.previewDefault(file, previewId);
  1863. setTimeout(function () {
  1864. readFile(i + 1);
  1865. self.updateFileDetails(numFiles);
  1866. }, 100);
  1867. self.raise('fileloaded', [file, previewId, i, reader]);
  1868. }
  1869. self.filestack.push(file);
  1870. }
  1871. readFile(0);
  1872. self.updateFileDetails(numFiles, false);
  1873. },
  1874. updateFileDetails: function (numFiles) {
  1875. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  1876. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1877. n = self.isUploadable ? fileStack.length : numFiles,
  1878. nFiles = previewCache.count(self.id) + n,
  1879. log = n > 1 ? self.getMsgSelected(nFiles) : label;
  1880. if (self.isError) {
  1881. self.$previewContainer.removeClass('loading');
  1882. self.$previewStatus.html('');
  1883. self.$captionContainer.find('.kv-caption-icon').hide();
  1884. } else {
  1885. self.showFileIcon();
  1886. }
  1887. self.setCaption(log, self.isError);
  1888. self.$container.removeClass('file-input-new file-input-ajax-new');
  1889. if (arguments.length === 1) {
  1890. self.raise('fileselect', [numFiles, label]);
  1891. }
  1892. if (previewCache.count(self.id)) {
  1893. self.initPreviewDeletes();
  1894. }
  1895. },
  1896. change: function (e) {
  1897. var self = this, $el = self.$element;
  1898. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1899. self.fileInputCleared = false;
  1900. return;
  1901. }
  1902. self.fileInputCleared = false;
  1903. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1904. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1905. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1906. ctr = self.filestack.length, isAjaxUpload = self.isUploadable,
  1907. throwError = function (mesg, file, previewId, index) {
  1908. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1909. p2 = {id: previewId, index: index, file: file, files: files};
  1910. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1911. };
  1912. self.reader = null;
  1913. self.resetUpload();
  1914. self.hideFileIcon();
  1915. if (self.isUploadable) {
  1916. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1917. }
  1918. if (isDragDrop) {
  1919. tfiles = [];
  1920. while (files[i]) {
  1921. f = files[i];
  1922. if (!f.type && f.size % 4096 === 0) {
  1923. folders++;
  1924. } else {
  1925. tfiles.push(f);
  1926. }
  1927. i++;
  1928. }
  1929. } else {
  1930. if (e.target.files === undefined) {
  1931. tfiles = e.target && e.target.value ? [
  1932. {name: e.target.value.replace(/^.+\\/, '')}
  1933. ] : [];
  1934. } else {
  1935. tfiles = e.target.files;
  1936. }
  1937. }
  1938. if (isEmpty(tfiles) || tfiles.length === 0) {
  1939. if (!isAjaxUpload) {
  1940. self.clear();
  1941. }
  1942. self.showFolderError(folders);
  1943. self.raise('fileselectnone');
  1944. return;
  1945. }
  1946. self.resetErrors();
  1947. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1948. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1949. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', total);
  1950. self.isError = throwError(msg, null, null, null);
  1951. self.$captionContainer.find('.kv-caption-icon').hide();
  1952. self.setCaption('', true);
  1953. self.setEllipsis();
  1954. self.$container.removeClass('file-input-new file-input-ajax-new');
  1955. return;
  1956. }
  1957. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1958. if (self.hasInitialPreview()) {
  1959. var out = previewCache.out(self.id);
  1960. $preview.html(out.content);
  1961. self.setCaption(out.caption);
  1962. self.initPreviewDeletes();
  1963. } else {
  1964. self.clearPreview();
  1965. }
  1966. if (isSingleUpload && ctr > 0) {
  1967. self.filestack = [];
  1968. }
  1969. } else {
  1970. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  1971. self.clearPreview();
  1972. self.filestack = [];
  1973. }
  1974. }
  1975. if (self.isPreviewable) {
  1976. self.readFiles(tfiles);
  1977. } else {
  1978. self.updateFileDetails(1);
  1979. }
  1980. self.showFolderError(folders);
  1981. },
  1982. validateImage: function (i, previewId) {
  1983. var self = this, $preview = self.$preview, params, w1, w2, $cap,
  1984. $thumb = $preview.find("#" + previewId), fname = 'Untitled',
  1985. $img = $thumb.find('img');
  1986. if (!$img.length) {
  1987. return;
  1988. }
  1989. handler($img, 'load', function () {
  1990. w1 = $thumb.width();
  1991. w2 = $preview.width();
  1992. if (w1 > w2) {
  1993. $img.css('width', '100%');
  1994. $thumb.css('width', '97%');
  1995. }
  1996. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1997. if ($cap.length) {
  1998. $cap.width($img.width());
  1999. fname = $cap.text();
  2000. $cap.attr('title', fname);
  2001. }
  2002. params = {ind: i, id: previewId};
  2003. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2004. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2005. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2006. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2007. self.raise('fileimageloaded', [previewId]);
  2008. objUrl.revokeObjectURL($img.attr('src'));
  2009. });
  2010. },
  2011. checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2012. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max',
  2013. limit = self[tag + 'Image' + type], $imgEl, isValid;
  2014. if (isEmpty(limit) || !$img.length) {
  2015. return;
  2016. }
  2017. $imgEl = $img[0];
  2018. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2019. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2020. if (isValid) {
  2021. return;
  2022. }
  2023. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2024. self.showUploadError(msg, params);
  2025. self.setThumbStatus($thumb, 'Error');
  2026. self.filestack[i] = null;
  2027. },
  2028. initCaption: function () {
  2029. var self = this, cap = self.initialCaption || '';
  2030. if (self.overwriteInitial || isEmpty(cap)) {
  2031. self.$caption.html('');
  2032. return false;
  2033. }
  2034. self.setCaption(cap);
  2035. return true;
  2036. },
  2037. setCaption: function (content, isError) {
  2038. var self = this, title, out;
  2039. if (isError) {
  2040. title = $('<div>' + self.msgValidationError + '</div>').text();
  2041. out = '<span class="' + self.msgValidationErrorClass + '">' +
  2042. self.msgValidationErrorIcon + title + '</span>';
  2043. } else {
  2044. if (isEmpty(content) || self.$caption.length === 0) {
  2045. return;
  2046. }
  2047. title = $('<div>' + content + '</div>').text();
  2048. out = self.getLayoutTemplate('icon') + title;
  2049. }
  2050. self.$caption.html(out);
  2051. self.$caption.attr('title', title);
  2052. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2053. self.setEllipsis();
  2054. },
  2055. initBrowse: function ($container) {
  2056. var self = this;
  2057. self.$btnFile = $container.find('.btn-file');
  2058. self.$btnFile.append(self.$element);
  2059. },
  2060. createContainer: function () {
  2061. var self = this,
  2062. $container = $(document.createElement("div"))
  2063. .attr({"class": 'file-input file-input-new'})
  2064. .html(self.renderMain());
  2065. self.$element.before($container);
  2066. self.initBrowse($container);
  2067. return $container;
  2068. },
  2069. refreshContainer: function () {
  2070. var self = this, $container = self.$container;
  2071. $container.before(self.$element);
  2072. $container.html(self.renderMain());
  2073. self.initBrowse($container);
  2074. },
  2075. renderMain: function () {
  2076. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  2077. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  2078. .repl('{dropClass}', dropCss) : '',
  2079. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2080. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  2081. return self.mainTemplate.repl('{class}', self.mainClass)
  2082. .repl('{preview}', preview)
  2083. .repl('{caption}', caption)
  2084. .repl('{upload}', self.renderUpload())
  2085. .repl('{remove}', self.renderRemove())
  2086. .repl('{cancel}', self.renderCancel())
  2087. .repl('{browse}', self.renderBrowse());
  2088. },
  2089. renderBrowse: function () {
  2090. var self = this, css = self.browseClass + ' btn-file', status = '';
  2091. if (self.isDisabled) {
  2092. status = ' disabled ';
  2093. }
  2094. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  2095. },
  2096. renderRemove: function () {
  2097. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  2098. if (!self.showRemove) {
  2099. return '';
  2100. }
  2101. if (self.isDisabled) {
  2102. status = ' disabled ';
  2103. }
  2104. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  2105. },
  2106. renderCancel: function () {
  2107. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  2108. if (!self.showCancel) {
  2109. return '';
  2110. }
  2111. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  2112. },
  2113. renderUpload: function () {
  2114. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  2115. if (!self.showUpload) {
  2116. return '';
  2117. }
  2118. if (self.isDisabled) {
  2119. status = ' disabled ';
  2120. }
  2121. if (!self.isUploadable || self.isDisabled) {
  2122. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  2123. } else {
  2124. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  2125. }
  2126. return content;
  2127. }
  2128. };
  2129. //FileInput plugin definition
  2130. $.fn.fileinput = function (option) {
  2131. if (!hasFileAPISupport() && !isIE(9)) {
  2132. return;
  2133. }
  2134. var args = Array.apply(null, arguments);
  2135. args.shift();
  2136. return this.each(function () {
  2137. var $this = $(this), data = $this.data('fileinput'), defaults,
  2138. options = typeof option === 'object' && option,
  2139. lang = options.language || $this.data('language') || 'en';
  2140. if (!data) {
  2141. defaults = $.extend({}, $.fn.fileinput.defaults);
  2142. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2143. defaults = $.extend(defaults, $.fn.fileinputLocales[lang]);
  2144. }
  2145. data = new FileInput(this, $.extend(defaults, options, $this.data()));
  2146. $this.data('fileinput', data);
  2147. }
  2148. if (typeof option === 'string') {
  2149. data[option].apply(data, args);
  2150. }
  2151. });
  2152. };
  2153. $.fn.fileinput.defaults = {
  2154. language: 'en',
  2155. showCaption: true,
  2156. showPreview: true,
  2157. showRemove: true,
  2158. showUpload: true,
  2159. showCancel: true,
  2160. showUploadedThumbs: true,
  2161. mainClass: '',
  2162. previewClass: '',
  2163. captionClass: '',
  2164. mainTemplate: null,
  2165. initialCaption: '',
  2166. initialPreview: [],
  2167. initialPreviewDelimiter: '*$$*',
  2168. initialPreviewConfig: [],
  2169. initialPreviewThumbTags: [],
  2170. previewThumbTags: {},
  2171. initialPreviewShowDelete: true,
  2172. deleteUrl: '',
  2173. deleteExtraData: {},
  2174. overwriteInitial: true,
  2175. layoutTemplates: defaultLayoutTemplates,
  2176. previewTemplates: defaultPreviewTemplates,
  2177. allowedPreviewTypes: defaultPreviewTypes,
  2178. allowedPreviewMimeTypes: null,
  2179. allowedFileTypes: null,
  2180. allowedFileExtensions: null,
  2181. customLayoutTags: {},
  2182. customPreviewTags: {},
  2183. previewSettings: defaultPreviewSettings,
  2184. fileTypeSettings: defaultFileTypeSettings,
  2185. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2186. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2187. browseClass: 'btn btn-primary',
  2188. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2189. removeClass: 'btn btn-default',
  2190. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2191. cancelClass: 'btn btn-default',
  2192. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2193. uploadClass: 'btn btn-default',
  2194. uploadUrl: null,
  2195. uploadAsync: true,
  2196. uploadExtraData: {},
  2197. minImageWidth: null,
  2198. minImageHeight: null,
  2199. maxImageWidth: null,
  2200. maxImageHeight: null,
  2201. maxFileSize: 0,
  2202. minFileCount: 0,
  2203. maxFileCount: 0,
  2204. msgValidationErrorClass: 'text-danger',
  2205. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2206. msgErrorClass: 'file-error-message',
  2207. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2208. progressCompleteClass: "progress-bar progress-bar-success",
  2209. previewFileType: 'image',
  2210. wrapTextLength: 250,
  2211. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2212. elCaptionContainer: null,
  2213. elCaptionText: null,
  2214. elPreviewContainer: null,
  2215. elPreviewImage: null,
  2216. elPreviewStatus: null,
  2217. elErrorContainer: null,
  2218. slugCallback: null,
  2219. dropZoneEnabled: true,
  2220. dropZoneTitleClass: 'file-drop-zone-title',
  2221. fileActionSettings: {},
  2222. otherActionButtons: '',
  2223. textEncoding: 'UTF-8',
  2224. ajaxSettings: {},
  2225. ajaxDeleteSettings: {},
  2226. showAjaxErrorDetails: true
  2227. };
  2228. $.fn.fileinputLocales.en = {
  2229. fileSingle: 'file',
  2230. filePlural: 'files',
  2231. browseLabel: 'Browse &hellip;',
  2232. removeLabel: 'Remove',
  2233. removeTitle: 'Clear selected files',
  2234. cancelLabel: 'Cancel',
  2235. cancelTitle: 'Abort ongoing upload',
  2236. uploadLabel: 'Upload',
  2237. uploadTitle: 'Upload selected files',
  2238. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2239. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2240. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2241. msgFileNotFound: 'File "{name}" not found!',
  2242. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2243. msgFileNotReadable: 'File "{name}" is not readable.',
  2244. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2245. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2246. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2247. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2248. msgValidationError: 'File Upload Error',
  2249. msgLoading: 'Loading file {index} of {files} &hellip;',
  2250. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2251. msgSelected: '{n} {files} selected',
  2252. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2253. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2254. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2255. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2256. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2257. dropZoneTitle: 'Drag & drop files here &hellip;'
  2258. };
  2259. $.extend($.fn.fileinput.defaults, $.fn.fileinputLocales.en);
  2260. $.fn.fileinput.Constructor = FileInput;
  2261. /**
  2262. * Convert automatically file inputs with class 'file'
  2263. * into a bootstrap fileinput control.
  2264. */
  2265. $(document).ready(function () {
  2266. var $input = $('input.file[type=file]');
  2267. if ($input.length) {
  2268. $input.fileinput();
  2269. }
  2270. });
  2271. })(window.jQuery);