fileinput.js 98 KB

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