fileinput.js 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.2.6
  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, fileCount;
  670. if (files && self.minFileCount > 0 && self.getFileCount(files.length) < self.minFileCount) {
  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 (self.minFileCount > 0 && self.getFileCount(totLen) < self.minFileCount) {
  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. if (!self.validateMinCount()) {
  864. return false;
  865. }
  866. self.cleanMemory($frame);
  867. $frame.fadeOut('slow', function () {
  868. self.filestack[ind] = undefined;
  869. self.clearObjects($frame);
  870. $frame.remove();
  871. var filestack = self.getFileStack(true), len = filestack.length,
  872. chk = previewCache.count(self.id);
  873. self.clearFileInput();
  874. if (len === 0 && chk === 0) {
  875. self.reset();
  876. } else {
  877. n = chk + len;
  878. cap = n > 1 ? self.getMsgSelected(n) : (filestack[0] ? filestack[0].name : '');
  879. self.setCaption(cap);
  880. }
  881. });
  882. });
  883. });
  884. self.$preview.find('.kv-file-upload').each(function () {
  885. var $el = $(this);
  886. handler($el, 'click', function () {
  887. var $frame = $el.closest('.file-preview-frame'),
  888. ind = $frame.attr('data-fileindex');
  889. self.uploadSingle(ind, self.filestack, false);
  890. });
  891. });
  892. },
  893. getMsgSelected: function (n) {
  894. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  895. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  896. },
  897. renderFileFooter: function (caption, width) {
  898. var self = this, config = self.fileActionSettings, footer, out,
  899. template = self.getLayoutTemplate('footer');
  900. if (self.isUploadable) {
  901. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false));
  902. out = footer.repl('{caption}', caption)
  903. .repl('{width}', width)
  904. .repl('{indicator}', config.indicatorNew)
  905. .repl('{indicatorTitle}', config.indicatorNewTitle);
  906. } else {
  907. out = template.repl('{actions}', '')
  908. .repl('{caption}', caption)
  909. .repl('{width}', width)
  910. .repl('{indicator}', '')
  911. .repl('{indicatorTitle}', '');
  912. }
  913. out = replaceTags(out, self.previewThumbTags);
  914. return out;
  915. },
  916. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  917. if (!showUpload && !showDelete) {
  918. return '';
  919. }
  920. var self = this,
  921. vUrl = url === false ? '' : ' data-url="' + url + '"',
  922. vKey = key === false ? '' : ' data-key="' + key + '"',
  923. btnDelete = self.getLayoutTemplate('actionDelete'),
  924. btnUpload = '',
  925. template = self.getLayoutTemplate('actions'),
  926. otherButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  927. config = self.fileActionSettings,
  928. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  929. btnDelete = btnDelete
  930. .repl('{removeClass}', removeClass)
  931. .repl('{removeIcon}', config.removeIcon)
  932. .repl('{removeTitle}', config.removeTitle)
  933. .repl('{dataUrl}', vUrl)
  934. .repl('{dataKey}', vKey);
  935. if (showUpload) {
  936. btnUpload = self.getLayoutTemplate('actionUpload')
  937. .repl('{uploadClass}', config.uploadClass)
  938. .repl('{uploadIcon}', config.uploadIcon)
  939. .repl('{uploadTitle}', config.uploadTitle);
  940. }
  941. return template
  942. .repl('{delete}', btnDelete)
  943. .repl('{upload}', btnUpload)
  944. .repl('{other}', otherButtons);
  945. },
  946. setThumbStatus: function ($thumb, status) {
  947. var self = this, icon = 'indicator' + status, msg = icon + 'Title',
  948. css = 'file-preview-' + status.toLowerCase(),
  949. $indicator = $thumb.find('.file-upload-indicator'),
  950. config = self.fileActionSettings;
  951. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  952. $indicator.html(config[icon]);
  953. $indicator.attr('title', config[msg]);
  954. $thumb.addClass(css);
  955. },
  956. clearPreview: function () {
  957. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  958. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  959. $thumbs.remove();
  960. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  961. self.resetUpload();
  962. }
  963. },
  964. initPreview: function (isInit) {
  965. var self = this, cap = self.initialCaption || '', out;
  966. if (!previewCache.count(self.id)) {
  967. self.clearPreview();
  968. if (isInit) {
  969. self.setCaption(cap);
  970. } else {
  971. self.initCaption();
  972. }
  973. return;
  974. }
  975. out = previewCache.out(self.id);
  976. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  977. self.$preview.html(out.content);
  978. self.setCaption(cap);
  979. if (!isEmpty(out.content)) {
  980. self.$container.removeClass('file-input-new');
  981. }
  982. },
  983. initPreviewDeletes: function () {
  984. var self = this, deleteExtraData = self.deleteExtraData || {},
  985. resetProgress = function () {
  986. if (self.$preview.find('.kv-file-remove').length === 0) {
  987. self.reset();
  988. self.initialCaption = '';
  989. }
  990. };
  991. self.$preview.find('.kv-file-remove').each(function () {
  992. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), len;
  993. if (isEmpty(vUrl) || vKey === undefined) {
  994. return;
  995. }
  996. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  997. settings, params, index = $frame.data('fileindex'), config, extraData;
  998. index = parseInt(index.replace('init_', ''));
  999. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1000. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1001. if (typeof extraData === "function") {
  1002. extraData = extraData();
  1003. }
  1004. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1005. settings = $.extend({
  1006. url: vUrl,
  1007. type: 'DELETE',
  1008. dataType: 'json',
  1009. data: $.extend({key: vKey}, extraData),
  1010. beforeSend: function (jqXHR) {
  1011. self.ajaxAborted = false;
  1012. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  1013. if (self.ajaxAborted) {
  1014. jqXHR.abort();
  1015. } else {
  1016. addCss($frame, 'file-uploading');
  1017. addCss($el, 'disabled');
  1018. }
  1019. },
  1020. success: function (data, textStatus, jqXHR) {
  1021. var n, cap;
  1022. if (isEmpty(data) || isEmpty(data.error)) {
  1023. previewCache.unset(self.id, index);
  1024. n = previewCache.count(self.id);
  1025. cap = n > 0 ? self.getMsgSelected(n) : '';
  1026. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  1027. self.setCaption(cap);
  1028. } else {
  1029. params.jqXHR = jqXHR;
  1030. params.response = data;
  1031. self.showError(data.error, params, 'filedeleteerror');
  1032. $frame.removeClass('file-uploading');
  1033. $el.removeClass('disabled');
  1034. resetProgress();
  1035. return;
  1036. }
  1037. $frame.removeClass('file-uploading').addClass('file-deleted');
  1038. $frame.fadeOut('slow', function () {
  1039. self.clearObjects($frame);
  1040. $frame.remove();
  1041. resetProgress();
  1042. if (!n && self.getFileStack().length === 0) {
  1043. self.setCaption('');
  1044. self.reset();
  1045. }
  1046. });
  1047. },
  1048. error: function (jqXHR, textStatus, errorThrown) {
  1049. var errMsg = self.parseError(jqXHR, errorThrown);
  1050. params.jqXHR = jqXHR;
  1051. params.response = {};
  1052. self.showError(errMsg, params, 'filedeleteerror');
  1053. $frame.removeClass('file-uploading');
  1054. resetProgress();
  1055. }
  1056. }, self.ajaxDeleteSettings);
  1057. handler($el, 'click', function () {
  1058. if (!self.validateMinCount()) {
  1059. return false;
  1060. }
  1061. $.ajax(settings);
  1062. });
  1063. });
  1064. },
  1065. clearObjects: function ($el) {
  1066. $el.find('video audio').each(function () {
  1067. this.pause();
  1068. $(this).remove();
  1069. });
  1070. $el.find('img object div').each(function () {
  1071. $(this).remove();
  1072. });
  1073. },
  1074. clearFileInput: function () {
  1075. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1076. if (isEmpty($el.val())) {
  1077. return;
  1078. }
  1079. // Fix for IE ver < 11, that does not clear file inputs
  1080. // Requires a sequence of steps to prevent IE crashing but
  1081. // still allow clearing of the file input.
  1082. if (self.isIE9 || self.isIE10) {
  1083. $srcFrm = $el.closest('form');
  1084. $tmpFrm = $(document.createElement('form'));
  1085. $tmpEl = $(document.createElement('div'));
  1086. $el.before($tmpEl);
  1087. if ($srcFrm.length) {
  1088. $srcFrm.after($tmpFrm);
  1089. } else {
  1090. $tmpEl.after($tmpFrm);
  1091. }
  1092. $tmpFrm.append($el).trigger('reset');
  1093. $tmpEl.before($el).remove();
  1094. $tmpFrm.remove();
  1095. } else { // normal input clear behavior for other sane browsers
  1096. $el.val('');
  1097. }
  1098. self.fileInputCleared = true;
  1099. },
  1100. resetUpload: function () {
  1101. var self = this;
  1102. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1103. self.uploadCount = 0;
  1104. self.uploadPercent = 0;
  1105. self.$btnUpload.removeAttr('disabled');
  1106. self.setProgress(0);
  1107. addCss(self.$progress, 'hide');
  1108. self.resetErrors(false);
  1109. self.ajaxAborted = false;
  1110. self.ajaxRequests = [];
  1111. },
  1112. cancel: function () {
  1113. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1114. if (len > 0) {
  1115. for (i = 0; i < len; i += 1) {
  1116. xhr[i].abort();
  1117. }
  1118. }
  1119. self.getThumbs().each(function () {
  1120. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1121. $thumb.removeClass('file-uploading');
  1122. if (self.filestack[ind] !== undefined) {
  1123. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1124. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1125. }
  1126. self.unlock();
  1127. });
  1128. },
  1129. cleanMemory: function ($thumb) {
  1130. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  1131. objUrl.revokeObjectURL(data);
  1132. },
  1133. hasInitialPreview: function () {
  1134. var self = this;
  1135. return !self.overwriteInitial && previewCache.count(self.id);
  1136. },
  1137. clear: function () {
  1138. var self = this, cap;
  1139. self.$btnUpload.removeAttr('disabled');
  1140. self.getThumbs().find('video,audio,img').each(function () {
  1141. self.cleanMemory($(this));
  1142. });
  1143. self.resetUpload();
  1144. self.filestack = [];
  1145. self.clearFileInput();
  1146. self.resetErrors(true);
  1147. self.raise('fileclear');
  1148. if (self.hasInitialPreview()) {
  1149. self.showFileIcon();
  1150. self.resetPreview();
  1151. self.setEllipsis();
  1152. self.initPreviewDeletes();
  1153. self.$container.removeClass('file-input-new');
  1154. } else {
  1155. self.getThumbs().each(function () {
  1156. self.clearObjects($(this));
  1157. });
  1158. if (self.isUploadable) {
  1159. previewCache.data[self.id] = {};
  1160. }
  1161. self.$preview.html('');
  1162. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1163. self.setCaption(cap);
  1164. self.setEllipsis();
  1165. self.$caption.attr('title', '');
  1166. addCss(self.$container, 'file-input-new');
  1167. }
  1168. if (self.$container.find('.file-preview-frame').length === 0) {
  1169. if (!self.initCaption()) {
  1170. self.$captionContainer.find('.kv-caption-icon').hide();
  1171. }
  1172. self.setEllipsis();
  1173. }
  1174. self.hideFileIcon();
  1175. self.raise('filecleared');
  1176. self.$captionContainer.focus();
  1177. self.setFileDropZoneTitle();
  1178. },
  1179. resetPreview: function () {
  1180. var self = this, out;
  1181. if (previewCache.count(self.id)) {
  1182. out = previewCache.out(self.id);
  1183. self.$preview.html(out.content);
  1184. self.setCaption(out.caption);
  1185. } else {
  1186. self.clearPreview();
  1187. self.initCaption();
  1188. }
  1189. },
  1190. resetPreviewThumbs: function (isAjax) {
  1191. var self = this, out;
  1192. if (isAjax) {
  1193. self.clearPreview();
  1194. self.filestack = [];
  1195. return;
  1196. }
  1197. if (self.hasInitialPreview()) {
  1198. out = previewCache.out(self.id);
  1199. self.$preview.html(out.content);
  1200. self.setCaption(out.caption);
  1201. self.initPreviewDeletes();
  1202. } else {
  1203. self.clearPreview();
  1204. }
  1205. },
  1206. reset: function () {
  1207. var self = this;
  1208. self.resetPreview();
  1209. self.setEllipsis();
  1210. self.$container.find('.fileinput-filename').text('');
  1211. self.raise('filereset');
  1212. addCss(self.$container, 'file-input-new');
  1213. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  1214. self.$container.removeClass('file-input-new');
  1215. }
  1216. self.setFileDropZoneTitle();
  1217. self.filestack = [];
  1218. self.formdata = {};
  1219. },
  1220. disable: function () {
  1221. var self = this;
  1222. self.isDisabled = true;
  1223. self.raise('filedisabled');
  1224. self.$element.attr('disabled', 'disabled');
  1225. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1226. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload, .file-preview-frame button").attr("disabled",
  1227. true);
  1228. self.initDragDrop();
  1229. },
  1230. enable: function () {
  1231. var self = this;
  1232. self.isDisabled = false;
  1233. self.raise('fileenabled');
  1234. self.$element.removeAttr('disabled');
  1235. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1236. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  1237. self.initDragDrop();
  1238. },
  1239. getThumbs: function (css) {
  1240. css = css || '';
  1241. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1242. },
  1243. getExtraData: function (previewId, index) {
  1244. var self = this, data = self.uploadExtraData;
  1245. if (typeof self.uploadExtraData === "function") {
  1246. data = self.uploadExtraData(previewId, index);
  1247. }
  1248. return data;
  1249. },
  1250. uploadExtra: function (previewId, index) {
  1251. var self = this, data = self.getExtraData(previewId, index);
  1252. if (data.length === 0) {
  1253. return;
  1254. }
  1255. $.each(data, function (key, value) {
  1256. self.formdata.append(key, value);
  1257. });
  1258. },
  1259. initXhr: function (xhrobj, factor) {
  1260. var self = this;
  1261. if (xhrobj.upload) {
  1262. xhrobj.upload.addEventListener('progress', function (event) {
  1263. var pct = 0, position = event.loaded || event.position, total = event.total;
  1264. if (event.lengthComputable) {
  1265. pct = Math.ceil(position / total * factor);
  1266. }
  1267. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1268. self.setProgress(self.uploadPercent);
  1269. }, false);
  1270. }
  1271. return xhrobj;
  1272. },
  1273. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1274. var self = this, settings;
  1275. self.raise('filepreajax', [previewId, index]);
  1276. self.uploadExtra(previewId, index);
  1277. settings = $.extend({
  1278. xhr: function () {
  1279. var xhrobj = $.ajaxSettings.xhr();
  1280. return self.initXhr(xhrobj, 98);
  1281. },
  1282. url: self.uploadUrl,
  1283. type: 'POST',
  1284. dataType: 'json',
  1285. data: self.formdata,
  1286. cache: false,
  1287. processData: false,
  1288. contentType: false,
  1289. beforeSend: fnBefore,
  1290. success: fnSuccess,
  1291. complete: fnComplete,
  1292. error: fnError
  1293. }, self.ajaxSettings);
  1294. self.ajaxRequests.push($.ajax(settings));
  1295. },
  1296. initUploadSuccess: function (out, $thumb, allFiles) {
  1297. var self = this, append, data, index, $newThumb, content, config, tags;
  1298. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1299. return;
  1300. }
  1301. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1302. self.hasInitData = true;
  1303. content = out.initialPreview || [];
  1304. config = out.initialPreviewConfig || [];
  1305. tags = out.initialPreviewThumbTags || [];
  1306. append = out.append === undefined || out.append ? true : false;
  1307. self.overwriteInitial = false;
  1308. if ($thumb !== undefined && !allFiles) {
  1309. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1310. data = previewCache.get(self.id, index, false);
  1311. $newThumb = $(data).hide();
  1312. $thumb.after($newThumb).fadeOut('slow', function () {
  1313. $newThumb.fadeIn('slow').css('display:inline-block');
  1314. self.initPreviewDeletes();
  1315. self.clearFileInput();
  1316. $thumb.remove();
  1317. });
  1318. } else {
  1319. if (allFiles) {
  1320. self.uploadCache.content.push(content[0]);
  1321. self.uploadCache.config.push(config[0]);
  1322. self.uploadCache.tags.push(tags[0]);
  1323. self.uploadCache.append = append;
  1324. } else {
  1325. previewCache.set(self.id, content, config, tags, append);
  1326. self.initPreview();
  1327. self.initPreviewDeletes();
  1328. }
  1329. }
  1330. }
  1331. },
  1332. initSuccessThumbs: function () {
  1333. var self = this;
  1334. self.getThumbs('.file-preview-success').each(function () {
  1335. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1336. $remove.removeAttr('disabled');
  1337. handler($remove, 'click', function () {
  1338. var out = self.raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1339. self.cleanMemory($thumb);
  1340. if (out === false) {
  1341. return;
  1342. }
  1343. $thumb.fadeOut('slow', function () {
  1344. $thumb.remove();
  1345. if (!self.$preview.find('.file-preview-frame').length) {
  1346. self.reset();
  1347. }
  1348. });
  1349. });
  1350. });
  1351. },
  1352. uploadSingle: function (i, files, allFiles) {
  1353. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1354. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1355. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1356. updateProgress, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1357. resetActions, fnBefore, fnSuccess, fnComplete, fnError, params = {id: previewId, index: i};
  1358. self.formdata = formdata;
  1359. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1360. return;
  1361. }
  1362. chkComplete = function () {
  1363. var $thumbs = self.getThumbs('.file-uploading');
  1364. if ($thumbs.length > 0 || self.fileBatchCompleted) {
  1365. return;
  1366. }
  1367. self.fileBatchCompleted = true;
  1368. setTimeout(function () {
  1369. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.tags,
  1370. self.uploadCache.append);
  1371. if (self.hasInitData) {
  1372. self.initPreview();
  1373. self.initPreviewDeletes();
  1374. }
  1375. self.setProgress(100);
  1376. self.unlock();
  1377. self.clearFileInput();
  1378. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1379. }, 100);
  1380. };
  1381. updateProgress = function () {
  1382. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1383. return;
  1384. }
  1385. self.uploadCount += 1;
  1386. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1387. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1388. self.setProgress(self.uploadPercent);
  1389. self.initPreviewDeletes();
  1390. };
  1391. resetActions = function () {
  1392. $btnUpload.removeAttr('disabled');
  1393. $btnDelete.removeAttr('disabled');
  1394. $thumb.removeClass('file-uploading');
  1395. };
  1396. fnBefore = function (jqXHR) {
  1397. outData = self.getOutData(jqXHR);
  1398. if (!$thumb.hasClass('file-preview-success')) {
  1399. self.setThumbStatus($thumb, 'Loading');
  1400. addCss($thumb, 'file-uploading');
  1401. }
  1402. $btnUpload.attr('disabled', true);
  1403. $btnDelete.attr('disabled', true);
  1404. if (!allFiles) {
  1405. self.lock();
  1406. }
  1407. self.raise('filepreupload', [outData, previewId, i]);
  1408. params = $.extend(params, outData);
  1409. if (self.abort(params)) {
  1410. jqXHR.abort();
  1411. self.setProgress(100);
  1412. }
  1413. };
  1414. fnSuccess = function (data, textStatus, jqXHR) {
  1415. outData = self.getOutData(jqXHR, data);
  1416. params = $.extend(params, outData);
  1417. setTimeout(function () {
  1418. if (isEmpty(data) || isEmpty(data.error)) {
  1419. self.setThumbStatus($thumb, 'Success');
  1420. $btnUpload.hide();
  1421. self.filestack[i] = undefined;
  1422. self.raise('fileuploaded', [outData, previewId, i]);
  1423. self.initUploadSuccess(data, $thumb, allFiles);
  1424. if (!allFiles) {
  1425. self.resetFileStack();
  1426. }
  1427. } else {
  1428. self.setThumbStatus($thumb, 'Error');
  1429. self.showUploadError(data.error, params);
  1430. }
  1431. }, 100);
  1432. };
  1433. fnComplete = function () {
  1434. setTimeout(function () {
  1435. updateProgress();
  1436. resetActions();
  1437. if (!allFiles) {
  1438. self.unlock(false);
  1439. } else {
  1440. chkComplete();
  1441. }
  1442. self.initSuccessThumbs();
  1443. }, 100);
  1444. };
  1445. fnError = function (jqXHR, textStatus, errorThrown) {
  1446. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1447. self.setThumbStatus($thumb, 'Error');
  1448. params = $.extend(params, self.getOutData(jqXHR));
  1449. self.showUploadError(errMsg, params);
  1450. };
  1451. formdata.append(self.uploadFileAttr, files[i]);
  1452. formdata.append('file_id', i);
  1453. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1454. },
  1455. uploadBatch: function () {
  1456. var self = this, files = self.filestack, total = files.length, config,
  1457. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1458. setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1459. params = {};
  1460. self.formdata = new FormData();
  1461. if (total === 0 || !hasPostData || self.abort(params)) {
  1462. return;
  1463. }
  1464. setAllUploaded = function () {
  1465. $.each(files, function (key) {
  1466. self.filestack[key] = undefined;
  1467. });
  1468. self.clearFileInput();
  1469. };
  1470. fnBefore = function (jqXHR) {
  1471. self.lock();
  1472. var outData = self.getOutData(jqXHR);
  1473. if (self.showPreview) {
  1474. self.getThumbs().each(function () {
  1475. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1476. $btnDelete = $thumb.find('.kv-file-remove');
  1477. if (!$thumb.hasClass('file-preview-success')) {
  1478. self.setThumbStatus($thumb, 'Loading');
  1479. addCss($thumb, 'file-uploading');
  1480. }
  1481. $btnUpload.attr('disabled', true);
  1482. $btnDelete.attr('disabled', true);
  1483. });
  1484. }
  1485. self.raise('filebatchpreupload', [outData]);
  1486. if (self.abort(outData)) {
  1487. jqXHR.abort();
  1488. }
  1489. };
  1490. fnSuccess = function (data, textStatus, jqXHR) {
  1491. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(),
  1492. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys, key = 0;
  1493. if (isEmpty(data) || isEmpty(data.error)) {
  1494. self.raise('filebatchuploadsuccess', [outData]);
  1495. setAllUploaded();
  1496. if (self.showPreview) {
  1497. $thumbs.each(function () {
  1498. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1499. $thumb.find('.kv-file-upload').hide();
  1500. self.setThumbStatus($thumb, 'Success');
  1501. $thumb.removeClass('file-uploading');
  1502. $btnUpload.removeAttr('disabled');
  1503. });
  1504. self.initUploadSuccess(data);
  1505. } else {
  1506. self.reset();
  1507. }
  1508. } else {
  1509. if (self.showPreview) {
  1510. $thumbs.each(function () {
  1511. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1512. $btnUpload = $thumb.find('.kv-file-upload');
  1513. $thumb.removeClass('file-uploading');
  1514. $btnUpload.removeAttr('disabled');
  1515. $btnDelete.removeAttr('disabled');
  1516. if (keys.length === 0) {
  1517. self.setThumbStatus($thumb, 'Error');
  1518. return;
  1519. }
  1520. if ($.inArray(key, keys) !== -1) {
  1521. self.setThumbStatus($thumb, 'Error');
  1522. } else {
  1523. $thumb.find('.kv-file-upload').hide();
  1524. self.setThumbStatus($thumb, 'Success');
  1525. self.filestack[key] = undefined;
  1526. }
  1527. key++;
  1528. });
  1529. self.initUploadSuccess(data);
  1530. }
  1531. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1532. }
  1533. };
  1534. fnComplete = function () {
  1535. self.setProgress(100);
  1536. self.unlock();
  1537. self.initSuccessThumbs();
  1538. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1539. self.clearFileInput();
  1540. };
  1541. fnError = function (jqXHR, textStatus, errorThrown) {
  1542. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1543. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1544. self.uploadFileCount = total - 1;
  1545. if (!self.showPreview) {
  1546. return;
  1547. }
  1548. self.getThumbs().each(function () {
  1549. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1550. $thumb.removeClass('file-uploading');
  1551. if (self.filestack[key] !== undefined) {
  1552. self.setThumbStatus($thumb, 'Error');
  1553. }
  1554. });
  1555. self.getThumbs().removeClass('file-uploading');
  1556. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1557. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1558. };
  1559. $.each(files, function (key, data) {
  1560. if (!isEmpty(files[key])) {
  1561. self.formdata.append(self.uploadFileAttr, data);
  1562. }
  1563. });
  1564. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1565. },
  1566. uploadExtraOnly: function () {
  1567. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1568. self.formdata = new FormData();
  1569. if (self.abort(params)) {
  1570. return;
  1571. }
  1572. fnBefore = function (jqXHR) {
  1573. self.lock();
  1574. var outData = self.getOutData(jqXHR);
  1575. self.raise('filebatchpreupload', [outData]);
  1576. self.setProgress(50);
  1577. params.data = outData;
  1578. params.xhr = jqXHR;
  1579. if (self.abort(params)) {
  1580. jqXHR.abort();
  1581. self.setProgress(100);
  1582. }
  1583. };
  1584. fnSuccess = function (data, textStatus, jqXHR) {
  1585. var outData = self.getOutData(jqXHR, data);
  1586. if (isEmpty(data) || isEmpty(data.error)) {
  1587. self.raise('filebatchuploadsuccess', [outData]);
  1588. self.clearFileInput();
  1589. self.initUploadSuccess(data);
  1590. } else {
  1591. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1592. }
  1593. };
  1594. fnComplete = function () {
  1595. self.setProgress(100);
  1596. self.unlock();
  1597. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1598. self.clearFileInput();
  1599. };
  1600. fnError = function (jqXHR, textStatus, errorThrown) {
  1601. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1602. params.data = outData;
  1603. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1604. };
  1605. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1606. },
  1607. hideFileIcon: function () {
  1608. if (this.overwriteInitial) {
  1609. this.$captionContainer.find('.kv-caption-icon').hide();
  1610. }
  1611. },
  1612. showFileIcon: function () {
  1613. this.$captionContainer.find('.kv-caption-icon').show();
  1614. },
  1615. resetErrors: function (fade) {
  1616. var self = this, $error = self.$errorContainer;
  1617. self.isError = false;
  1618. self.$container.removeClass('has-error');
  1619. $error.html('');
  1620. if (fade) {
  1621. $error.fadeOut('slow');
  1622. } else {
  1623. $error.hide();
  1624. }
  1625. },
  1626. showFolderError: function (folders) {
  1627. var self = this, $error = self.$errorContainer;
  1628. if (!folders) {
  1629. return;
  1630. }
  1631. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1632. $error.fadeIn(800);
  1633. addCss(self.$container, 'has-error');
  1634. self.raise('filefoldererror', [folders]);
  1635. },
  1636. showUploadError: function (msg, params, event) {
  1637. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1638. if ($error.find('ul').length === 0) {
  1639. $error.html('<ul><li>' + msg + '</li></ul>');
  1640. } else {
  1641. $error.find('ul').append('<li>' + msg + '</li>');
  1642. }
  1643. $error.fadeIn(800);
  1644. self.raise(ev, [params]);
  1645. self.$container.removeClass('file-input-new');
  1646. addCss(self.$container, 'has-error');
  1647. return true;
  1648. },
  1649. showError: function (msg, params, event) {
  1650. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1651. params = params || {};
  1652. params.reader = self.reader;
  1653. $error.html(msg);
  1654. $error.fadeIn(800);
  1655. self.raise(ev, [params]);
  1656. if (!self.isUploadable) {
  1657. self.clearFileInput();
  1658. }
  1659. self.$container.removeClass('file-input-new');
  1660. addCss(self.$container, 'has-error');
  1661. self.$btnUpload.attr('disabled', true);
  1662. return true;
  1663. },
  1664. errorHandler: function (evt, caption) {
  1665. var self = this, err = evt.target.error;
  1666. switch (err.code) {
  1667. case err.NOT_FOUND_ERR:
  1668. self.showError(self.msgFileNotFound.replace('{name}', caption));
  1669. break;
  1670. case err.SECURITY_ERR:
  1671. self.showError(self.msgFileSecured.replace('{name}', caption));
  1672. break;
  1673. case err.NOT_READABLE_ERR:
  1674. self.showError(self.msgFileNotReadable.replace('{name}', caption));
  1675. break;
  1676. case err.ABORT_ERR:
  1677. self.showError(self.msgFilePreviewAborted.replace('{name}', caption));
  1678. break;
  1679. default:
  1680. self.showError(self.msgFilePreviewError.replace('{name}', caption));
  1681. }
  1682. },
  1683. parseFileType: function (file) {
  1684. var self = this, isValid, vType, cat, i;
  1685. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1686. cat = defaultPreviewTypes[i];
  1687. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1688. vType = isValid(file.type, file.name) ? cat : '';
  1689. if (!isEmpty(vType)) {
  1690. return vType;
  1691. }
  1692. }
  1693. return 'other';
  1694. },
  1695. previewDefault: function (file, previewId, isDisabled) {
  1696. if (!this.showPreview) {
  1697. return;
  1698. }
  1699. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1700. config = self.previewSettings.other || defaultPreviewSettings.other,
  1701. footer = self.renderFileFooter(file.name, config.width),
  1702. previewOtherTemplate = self.getPreviewTemplate('other'),
  1703. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1704. frameClass = '';
  1705. if (isDisabled === true) {
  1706. frameClass = ' btn disabled';
  1707. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1708. }
  1709. self.$preview.append("\n" + previewOtherTemplate
  1710. .repl('{previewId}', previewId)
  1711. .repl('{frameClass}', frameClass)
  1712. .repl('{fileindex}', ind)
  1713. .repl('{caption}', self.slug(file.name))
  1714. .repl('{width}', config.width)
  1715. .repl('{height}', config.height)
  1716. .repl('{type}', file.type)
  1717. .repl('{data}', data)
  1718. .repl('{footer}', footer));
  1719. },
  1720. previewFile: function (i, file, theFile, previewId, data) {
  1721. if (!this.showPreview) {
  1722. return;
  1723. }
  1724. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1725. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1726. tmplt = self.getPreviewTemplate(cat),
  1727. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1728. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1729. chkTypes = types.indexOf(cat) >= 0, id, height,
  1730. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && mimes.indexOf(file.type) !== -1),
  1731. footer = self.renderFileFooter(caption, config.width), modal = '',
  1732. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1733. if (chkTypes && chkMimes) {
  1734. if (cat === 'text') {
  1735. strText = htmlEncode(theFile.target.result);
  1736. if (strText.length > wrapLen) {
  1737. id = 'text-' + uniqId();
  1738. height = window.innerHeight * 0.75;
  1739. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1740. .repl('{title}', caption)
  1741. .repl('{height}', height)
  1742. .repl('{body}', strText);
  1743. wrapInd = wrapInd
  1744. .repl('{title}', caption)
  1745. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1746. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1747. }
  1748. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1749. .repl('{frameClass}', '')
  1750. .repl('{type}', file.type).repl('{width}', config.width)
  1751. .repl('{height}', config.height).repl('{data}', strText)
  1752. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1753. } else {
  1754. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1755. .repl('{frameClass}', '')
  1756. .repl('{type}', file.type).repl('{data}', data)
  1757. .repl('{width}', config.width).repl('{height}', config.height)
  1758. .repl('{footer}', footer).repl('{fileindex}', ind);
  1759. }
  1760. self.$preview.append("\n" + content);
  1761. self.validateImage(i, previewId);
  1762. } else {
  1763. self.previewDefault(file, previewId);
  1764. }
  1765. },
  1766. slugDefault: function (text) {
  1767. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1768. },
  1769. getFileStack: function (skipNull) {
  1770. var self = this, status;
  1771. return self.filestack.filter(function (n) {
  1772. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  1773. });
  1774. },
  1775. readFiles: function (files) {
  1776. this.reader = new FileReader();
  1777. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1778. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1779. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1780. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1781. throwError = function (msg, file, previewId, index) {
  1782. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1783. p2 = {id: previewId, index: index, file: file, files: files};
  1784. self.previewDefault(file, previewId, true);
  1785. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1786. };
  1787. function readFile(i) {
  1788. if (isEmpty($el.attr('multiple'))) {
  1789. numFiles = 1;
  1790. }
  1791. if (i >= numFiles) {
  1792. if (self.isUploadable && self.filestack.length > 0) {
  1793. self.raise('filebatchselected', [self.getFileStack()]);
  1794. } else {
  1795. self.raise('filebatchselected', [files]);
  1796. }
  1797. $container.removeClass('loading');
  1798. $status.html('');
  1799. return;
  1800. }
  1801. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1802. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1803. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1804. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1805. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1806. if (!isEmpty(fileExt)) {
  1807. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1808. }
  1809. fileSize = fileSize.toFixed(2);
  1810. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1811. msg = self.msgSizeTooLarge.replace('{name}', caption)
  1812. .replace('{size}', fileSize)
  1813. .replace('{maxSize}', self.maxFileSize);
  1814. self.isError = throwError(msg, file, previewId, i);
  1815. return;
  1816. }
  1817. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1818. for (j = 0; j < fileTypes.length; j += 1) {
  1819. typ = fileTypes[j];
  1820. checkFile = settings[typ];
  1821. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1822. fileCount += isEmpty(chk) ? 0 : chk.length;
  1823. }
  1824. if (fileCount === 0) {
  1825. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  1826. self.isError = throwError(msg, file, previewId, i);
  1827. return;
  1828. }
  1829. }
  1830. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1831. chk = caption.match(fileExtExpr);
  1832. fileCount += isEmpty(chk) ? 0 : chk.length;
  1833. if (fileCount === 0) {
  1834. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  1835. strExt);
  1836. self.isError = throwError(msg, file, previewId, i);
  1837. return;
  1838. }
  1839. }
  1840. if (!self.showPreview) {
  1841. self.filestack.push(file);
  1842. setTimeout(readFile(i + 1), 100);
  1843. self.raise('fileloaded', [file, previewId, i, reader]);
  1844. return;
  1845. }
  1846. if ($preview.length > 0 && FileReader !== undefined) {
  1847. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  1848. $container.addClass('loading');
  1849. reader.onerror = function (evt) {
  1850. self.errorHandler(evt, caption);
  1851. };
  1852. reader.onload = function (theFile) {
  1853. self.previewFile(i, file, theFile, previewId, previewData);
  1854. self.initFileActions();
  1855. };
  1856. reader.onloadend = function () {
  1857. msg = msgProgress
  1858. .replace('{index}', i + 1).replace('{files}', numFiles)
  1859. .replace('{percent}', 50).replace('{name}', caption);
  1860. setTimeout(function () {
  1861. $status.html(msg);
  1862. self.updateFileDetails(numFiles);
  1863. readFile(i + 1);
  1864. }, 100);
  1865. self.raise('fileloaded', [file, previewId, i, reader]);
  1866. };
  1867. reader.onprogress = function (data) {
  1868. if (data.lengthComputable) {
  1869. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1870. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  1871. .replace('{percent}', progress).replace('{name}', caption);
  1872. setTimeout(function () {
  1873. $status.html(msg);
  1874. }, 100);
  1875. }
  1876. };
  1877. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1878. if (isText(file.type, caption)) {
  1879. reader.readAsText(file, self.textEncoding);
  1880. } else {
  1881. reader.readAsArrayBuffer(file);
  1882. }
  1883. } else {
  1884. self.previewDefault(file, previewId);
  1885. setTimeout(function () {
  1886. readFile(i + 1);
  1887. self.updateFileDetails(numFiles);
  1888. }, 100);
  1889. self.raise('fileloaded', [file, previewId, i, reader]);
  1890. }
  1891. self.filestack.push(file);
  1892. }
  1893. readFile(0);
  1894. self.updateFileDetails(numFiles, false);
  1895. },
  1896. updateFileDetails: function (numFiles) {
  1897. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  1898. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1899. n = self.isUploadable ? fileStack.length : numFiles,
  1900. nFiles = previewCache.count(self.id) + n,
  1901. log = n > 1 ? self.getMsgSelected(nFiles) : label;
  1902. if (self.isError) {
  1903. self.$previewContainer.removeClass('loading');
  1904. self.$previewStatus.html('');
  1905. self.$captionContainer.find('.kv-caption-icon').hide();
  1906. } else {
  1907. self.showFileIcon();
  1908. }
  1909. self.setCaption(log, self.isError);
  1910. self.$container.removeClass('file-input-new file-input-ajax-new');
  1911. if (arguments.length === 1) {
  1912. self.raise('fileselect', [numFiles, label]);
  1913. }
  1914. if (previewCache.count(self.id)) {
  1915. self.initPreviewDeletes();
  1916. }
  1917. },
  1918. validateMinCount: function() {
  1919. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  1920. if (self.validateInitialCount && self.minFileCount > 0 && self.getFileCount(len - 1) < self.minFileCount) {
  1921. self.noFilesError({});
  1922. return false;
  1923. }
  1924. return true;
  1925. },
  1926. getFileCount: function(fileCount) {
  1927. var self = this, addCount = 0;
  1928. if (self.validateInitialCount && !self.overwriteInitial) {
  1929. addCount = previewCache.count(self.id);
  1930. fileCount += addCount;
  1931. }
  1932. return fileCount;
  1933. },
  1934. change: function (e) {
  1935. var self = this, $el = self.$element;
  1936. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1937. self.fileInputCleared = false;
  1938. return;
  1939. }
  1940. self.fileInputCleared = false;
  1941. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1942. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1943. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, n, folders = 0,
  1944. ctr = self.filestack.length, isAjaxUpload = self.isUploadable, len,
  1945. flagSingle = (isSingleUpload && ctr > 0),
  1946. throwError = function (mesg, file, previewId, index) {
  1947. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1948. p2 = {id: previewId, index: index, file: file, files: files};
  1949. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1950. };
  1951. self.reader = null;
  1952. self.resetUpload();
  1953. self.hideFileIcon();
  1954. if (self.isUploadable) {
  1955. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1956. }
  1957. if (isDragDrop) {
  1958. tfiles = [];
  1959. while (files[i]) {
  1960. f = files[i];
  1961. if (!f.type && f.size % 4096 === 0) {
  1962. folders++;
  1963. } else {
  1964. tfiles.push(f);
  1965. }
  1966. i++;
  1967. }
  1968. } else {
  1969. if (e.target.files === undefined) {
  1970. tfiles = e.target && e.target.value ? [
  1971. {name: e.target.value.replace(/^.+\\/, '')}
  1972. ] : [];
  1973. } else {
  1974. tfiles = e.target.files;
  1975. }
  1976. }
  1977. if (isEmpty(tfiles) || tfiles.length === 0) {
  1978. if (!isAjaxUpload) {
  1979. self.clear();
  1980. }
  1981. self.showFolderError(folders);
  1982. self.raise('fileselectnone');
  1983. return;
  1984. }
  1985. self.resetErrors();
  1986. len = tfiles.length;
  1987. total = self.isUploadable ? self.getFileStack().length + len : len;
  1988. total = self.getFileCount(total);
  1989. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1990. if (!self.autoReplace || len > self.maxFileCount) {
  1991. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  1992. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  1993. self.isError = throwError(msg, null, null, null);
  1994. self.$captionContainer.find('.kv-caption-icon').hide();
  1995. self.setCaption('', true);
  1996. self.setEllipsis();
  1997. self.$container.removeClass('file-input-new file-input-ajax-new');
  1998. return;
  1999. }
  2000. if (total > self.maxFileCount) {
  2001. self.resetPreviewThumbs(isAjaxUpload);
  2002. }
  2003. } else {
  2004. if (!isAjaxUpload || flagSingle) {
  2005. self.resetPreviewThumbs(false);
  2006. if (flagSingle) {
  2007. self.filestack = [];
  2008. }
  2009. } else {
  2010. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2011. self.resetPreviewThumbs(true);
  2012. }
  2013. }
  2014. }
  2015. if (self.isPreviewable) {
  2016. self.readFiles(tfiles);
  2017. } else {
  2018. self.updateFileDetails(1);
  2019. }
  2020. self.showFolderError(folders);
  2021. },
  2022. validateImage: function (i, previewId) {
  2023. var self = this, $preview = self.$preview, params, w1, w2, $cap,
  2024. $thumb = $preview.find("#" + previewId), fname = 'Untitled',
  2025. $img = $thumb.find('img');
  2026. if (!$img.length) {
  2027. return;
  2028. }
  2029. handler($img, 'load', function () {
  2030. w1 = $thumb.width();
  2031. w2 = $preview.width();
  2032. if (w1 > w2) {
  2033. $img.css('width', '100%');
  2034. $thumb.css('width', '97%');
  2035. }
  2036. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  2037. if ($cap.length) {
  2038. $cap.width($img.width());
  2039. fname = $cap.text();
  2040. $cap.attr('title', fname);
  2041. }
  2042. params = {ind: i, id: previewId};
  2043. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2044. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2045. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2046. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2047. self.raise('fileimageloaded', [previewId]);
  2048. objUrl.revokeObjectURL($img.attr('src'));
  2049. });
  2050. },
  2051. checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2052. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max',
  2053. limit = self[tag + 'Image' + type], $imgEl, isValid;
  2054. if (isEmpty(limit) || !$img.length) {
  2055. return;
  2056. }
  2057. $imgEl = $img[0];
  2058. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2059. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2060. if (isValid) {
  2061. return;
  2062. }
  2063. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2064. self.showUploadError(msg, params);
  2065. self.setThumbStatus($thumb, 'Error');
  2066. self.filestack[i] = null;
  2067. },
  2068. initCaption: function () {
  2069. var self = this, cap = self.initialCaption || '';
  2070. if (self.overwriteInitial || isEmpty(cap)) {
  2071. self.$caption.html('');
  2072. return false;
  2073. }
  2074. self.setCaption(cap);
  2075. return true;
  2076. },
  2077. setCaption: function (content, isError) {
  2078. var self = this, title, out;
  2079. if (isError) {
  2080. title = $('<div>' + self.msgValidationError + '</div>').text();
  2081. out = '<span class="' + self.msgValidationErrorClass + '">' +
  2082. self.msgValidationErrorIcon + title + '</span>';
  2083. } else {
  2084. if (isEmpty(content) || self.$caption.length === 0) {
  2085. return;
  2086. }
  2087. title = $('<div>' + content + '</div>').text();
  2088. out = self.getLayoutTemplate('icon') + title;
  2089. }
  2090. self.$caption.html(out);
  2091. self.$caption.attr('title', title);
  2092. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2093. self.setEllipsis();
  2094. },
  2095. initBrowse: function ($container) {
  2096. var self = this;
  2097. self.$btnFile = $container.find('.btn-file');
  2098. self.$btnFile.append(self.$element);
  2099. },
  2100. createContainer: function () {
  2101. var self = this,
  2102. $container = $(document.createElement("div"))
  2103. .attr({"class": 'file-input file-input-new'})
  2104. .html(self.renderMain());
  2105. self.$element.before($container);
  2106. self.initBrowse($container);
  2107. return $container;
  2108. },
  2109. refreshContainer: function () {
  2110. var self = this, $container = self.$container;
  2111. $container.before(self.$element);
  2112. $container.html(self.renderMain());
  2113. self.initBrowse($container);
  2114. },
  2115. renderMain: function () {
  2116. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  2117. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  2118. .repl('{dropClass}', dropCss) : '',
  2119. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2120. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  2121. return self.mainTemplate.repl('{class}', self.mainClass)
  2122. .repl('{preview}', preview)
  2123. .repl('{caption}', caption)
  2124. .repl('{upload}', self.renderUpload())
  2125. .repl('{remove}', self.renderRemove())
  2126. .repl('{cancel}', self.renderCancel())
  2127. .repl('{browse}', self.renderBrowse());
  2128. },
  2129. renderBrowse: function () {
  2130. var self = this, css = self.browseClass + ' btn-file', status = '';
  2131. if (self.isDisabled) {
  2132. status = ' disabled ';
  2133. }
  2134. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  2135. },
  2136. renderRemove: function () {
  2137. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  2138. if (!self.showRemove) {
  2139. return '';
  2140. }
  2141. if (self.isDisabled) {
  2142. status = ' disabled ';
  2143. }
  2144. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  2145. },
  2146. renderCancel: function () {
  2147. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  2148. if (!self.showCancel) {
  2149. return '';
  2150. }
  2151. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  2152. },
  2153. renderUpload: function () {
  2154. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  2155. if (!self.showUpload) {
  2156. return '';
  2157. }
  2158. if (self.isDisabled) {
  2159. status = ' disabled ';
  2160. }
  2161. if (!self.isUploadable || self.isDisabled) {
  2162. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  2163. } else {
  2164. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  2165. }
  2166. return content;
  2167. }
  2168. };
  2169. //FileInput plugin definition
  2170. $.fn.fileinput = function (option) {
  2171. if (!hasFileAPISupport() && !isIE(9)) {
  2172. return;
  2173. }
  2174. var args = Array.apply(null, arguments);
  2175. args.shift();
  2176. return this.each(function () {
  2177. var $this = $(this), data = $this.data('fileinput'), defaults,
  2178. options = typeof option === 'object' && option,
  2179. lang = options.language || $this.data('language') || 'en';
  2180. if (!data) {
  2181. defaults = $.extend({}, $.fn.fileinput.defaults);
  2182. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2183. defaults = $.extend(defaults, $.fn.fileinputLocales[lang]);
  2184. }
  2185. data = new FileInput(this, $.extend(defaults, options, $this.data()));
  2186. $this.data('fileinput', data);
  2187. }
  2188. if (typeof option === 'string') {
  2189. data[option].apply(data, args);
  2190. }
  2191. });
  2192. };
  2193. $.fn.fileinput.defaults = {
  2194. language: 'en',
  2195. showCaption: true,
  2196. showPreview: true,
  2197. showRemove: true,
  2198. showUpload: true,
  2199. showCancel: true,
  2200. showUploadedThumbs: true,
  2201. autoReplace: false,
  2202. mainClass: '',
  2203. previewClass: '',
  2204. captionClass: '',
  2205. mainTemplate: null,
  2206. initialCaption: '',
  2207. initialPreview: [],
  2208. initialPreviewDelimiter: '*$$*',
  2209. initialPreviewConfig: [],
  2210. initialPreviewThumbTags: [],
  2211. previewThumbTags: {},
  2212. initialPreviewShowDelete: true,
  2213. deleteUrl: '',
  2214. deleteExtraData: {},
  2215. overwriteInitial: true,
  2216. layoutTemplates: defaultLayoutTemplates,
  2217. previewTemplates: defaultPreviewTemplates,
  2218. allowedPreviewTypes: defaultPreviewTypes,
  2219. allowedPreviewMimeTypes: null,
  2220. allowedFileTypes: null,
  2221. allowedFileExtensions: null,
  2222. customLayoutTags: {},
  2223. customPreviewTags: {},
  2224. previewSettings: defaultPreviewSettings,
  2225. fileTypeSettings: defaultFileTypeSettings,
  2226. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2227. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2228. browseClass: 'btn btn-primary',
  2229. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2230. removeClass: 'btn btn-default',
  2231. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2232. cancelClass: 'btn btn-default',
  2233. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2234. uploadClass: 'btn btn-default',
  2235. uploadUrl: null,
  2236. uploadAsync: true,
  2237. uploadExtraData: {},
  2238. minImageWidth: null,
  2239. minImageHeight: null,
  2240. maxImageWidth: null,
  2241. maxImageHeight: null,
  2242. maxFileSize: 0,
  2243. minFileCount: 0,
  2244. maxFileCount: 0,
  2245. validateInitialCount: false,
  2246. msgValidationErrorClass: 'text-danger',
  2247. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2248. msgErrorClass: 'file-error-message',
  2249. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2250. progressCompleteClass: "progress-bar progress-bar-success",
  2251. previewFileType: 'image',
  2252. wrapTextLength: 250,
  2253. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2254. elCaptionContainer: null,
  2255. elCaptionText: null,
  2256. elPreviewContainer: null,
  2257. elPreviewImage: null,
  2258. elPreviewStatus: null,
  2259. elErrorContainer: null,
  2260. slugCallback: null,
  2261. dropZoneEnabled: true,
  2262. dropZoneTitleClass: 'file-drop-zone-title',
  2263. fileActionSettings: {},
  2264. otherActionButtons: '',
  2265. textEncoding: 'UTF-8',
  2266. ajaxSettings: {},
  2267. ajaxDeleteSettings: {},
  2268. showAjaxErrorDetails: true
  2269. };
  2270. $.fn.fileinputLocales.en = {
  2271. fileSingle: 'file',
  2272. filePlural: 'files',
  2273. browseLabel: 'Browse &hellip;',
  2274. removeLabel: 'Remove',
  2275. removeTitle: 'Clear selected files',
  2276. cancelLabel: 'Cancel',
  2277. cancelTitle: 'Abort ongoing upload',
  2278. uploadLabel: 'Upload',
  2279. uploadTitle: 'Upload selected files',
  2280. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  2281. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  2282. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  2283. msgFileNotFound: 'File "{name}" not found!',
  2284. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2285. msgFileNotReadable: 'File "{name}" is not readable.',
  2286. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2287. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2288. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2289. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2290. msgValidationError: 'File Upload Error',
  2291. msgLoading: 'Loading file {index} of {files} &hellip;',
  2292. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2293. msgSelected: '{n} {files} selected',
  2294. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2295. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2296. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2297. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2298. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2299. dropZoneTitle: 'Drag & drop files here &hellip;'
  2300. };
  2301. $.extend($.fn.fileinput.defaults, $.fn.fileinputLocales.en);
  2302. $.fn.fileinput.Constructor = FileInput;
  2303. /**
  2304. * Convert automatically file inputs with class 'file'
  2305. * into a bootstrap fileinput control.
  2306. */
  2307. $(document).ready(function () {
  2308. var $input = $('input.file[type=file]');
  2309. if ($input.length) {
  2310. $input.fileinput();
  2311. }
  2312. });
  2313. })(window.jQuery);