fileinput.js 111 KB

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