fileinput.js 101 KB

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