fileinput.js 98 KB

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