fileinput.js 98 KB

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