fileinput.js 100 KB

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