fileinput.js 109 KB

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