fileinput.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  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 drop');
  777. $(document).off('dragenter dragover drop');
  778. self.listen();
  779. self.setFileDropZoneTitle();
  780. },
  781. initDragDrop: function () {
  782. var self = this, $zone = self.$container.find('.file-drop-zone');
  783. $zone.off('dragenter dragover drop');
  784. $(document).off('dragenter dragover drop');
  785. $zone.on('dragenter dragover', function (e) {
  786. e.stopPropagation();
  787. e.preventDefault();
  788. if (self.isDisabled) {
  789. return;
  790. }
  791. addCss($(this), 'highlighted');
  792. });
  793. $zone.on('dragleave', function (e) {
  794. e.stopPropagation();
  795. e.preventDefault();
  796. if (self.isDisabled) {
  797. return;
  798. }
  799. $(this).removeClass('highlighted');
  800. });
  801. $zone.on('drop', function (e) {
  802. e.preventDefault();
  803. if (self.isDisabled) {
  804. return;
  805. }
  806. self.change(e, 'dragdrop');
  807. $(this).removeClass('highlighted');
  808. });
  809. $(document).on('dragenter dragover drop', function (e) {
  810. e.stopPropagation();
  811. e.preventDefault();
  812. });
  813. },
  814. setFileDropZoneTitle: function () {
  815. var self = this, $zone = self.$container.find('.file-drop-zone');
  816. $zone.find('.' + self.dropZoneTitleClass).remove();
  817. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  818. return;
  819. }
  820. if ($zone.find('.file-preview-frame').length === 0) {
  821. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  822. }
  823. self.$container.removeClass('file-input-new');
  824. addCss(self.$container, 'file-input-ajax-new');
  825. },
  826. initFileActions: function () {
  827. var self = this;
  828. self.$preview.find('.kv-file-remove').each(function () {
  829. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  830. ind = $frame.attr('data-fileindex'), n, cap;
  831. $el.off('click').on('click', function () {
  832. $frame.fadeOut('slow', function () {
  833. self.filestack[ind] = undefined;
  834. self.clearObjects($frame);
  835. $frame.remove();
  836. var filestack = self.getFileStack(), len = filestack.length,
  837. chk = previewCache.count(self.id);
  838. self.clearFileInput();
  839. if (len === 0 && chk === 0) {
  840. self.reset();
  841. } else {
  842. n = chk + len;
  843. cap = n > 1 ? self.getMsgSelected(n) : filestack[0].name;
  844. self.setCaption(cap);
  845. }
  846. });
  847. });
  848. });
  849. self.$preview.find('.kv-file-upload').each(function () {
  850. var $el = $(this);
  851. $el.off('click').on('click', function () {
  852. var $frame = $el.closest('.file-preview-frame'),
  853. ind = $frame.attr('data-fileindex');
  854. self.uploadSingle(ind, self.filestack, false);
  855. });
  856. });
  857. },
  858. getMsgSelected: function (n) {
  859. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  860. return self.msgSelected.repl('{n}', n).repl('{files}', strFiles);
  861. },
  862. renderFileFooter: function (caption, width) {
  863. var self = this, config = self.fileActionSettings, footer, out,
  864. template = self.getLayoutTemplate('footer');
  865. if (self.isUploadable) {
  866. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false));
  867. out = footer.repl('{caption}', caption)
  868. .repl('{width}', width)
  869. .repl('{indicator}', config.indicatorNew)
  870. .repl('{indicatorTitle}', config.indicatorNewTitle);
  871. } else {
  872. out = template.repl('{actions}', '')
  873. .repl('{caption}', caption)
  874. .repl('{width}', width)
  875. .repl('{indicator}', '')
  876. .repl('{indicatorTitle}', '');
  877. }
  878. out = replaceTags(out, self.previewThumbTags);
  879. return out;
  880. },
  881. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  882. if (!showUpload && !showDelete) {
  883. return '';
  884. }
  885. var self = this,
  886. vUrl = url === false ? '' : ' data-url="' + url + '"',
  887. vKey = key === false ? '' : ' data-key="' + key + '"',
  888. btnDelete = self.getLayoutTemplate('actionDelete'),
  889. btnUpload = '',
  890. template = self.getLayoutTemplate('actions'),
  891. otherButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  892. config = self.fileActionSettings,
  893. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  894. btnDelete = btnDelete
  895. .repl('{removeClass}', removeClass)
  896. .repl('{removeIcon}', config.removeIcon)
  897. .repl('{removeTitle}', config.removeTitle)
  898. .repl('{dataUrl}', vUrl)
  899. .repl('{dataKey}', vKey);
  900. if (showUpload) {
  901. btnUpload = self.getLayoutTemplate('actionUpload')
  902. .repl('{uploadClass}', config.uploadClass)
  903. .repl('{uploadIcon}', config.uploadIcon)
  904. .repl('{uploadTitle}', config.uploadTitle);
  905. }
  906. return template
  907. .repl('{delete}', btnDelete)
  908. .repl('{upload}', btnUpload)
  909. .repl('{other}', otherButtons);
  910. },
  911. setThumbStatus: function ($thumb, status) {
  912. var self = this, icon = 'indicator' + status, msg = icon + 'Title',
  913. css = 'file-preview-' + status.toLowerCase(),
  914. $indicator = $thumb.find('.file-upload-indicator'),
  915. config = self.fileActionSettings;
  916. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  917. $indicator.html(config[icon]);
  918. $indicator.attr('title', config[msg]);
  919. $thumb.addClass(css);
  920. },
  921. clearPreview: function () {
  922. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  923. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  924. $thumbs.remove();
  925. },
  926. initPreview: function (isInit) {
  927. var self = this, cap = self.initialCaption || '', out;
  928. if (!previewCache.count(self.id)) {
  929. self.clearPreview();
  930. if (isInit) {
  931. self.setCaption(cap);
  932. } else {
  933. self.initCaption();
  934. }
  935. return;
  936. }
  937. out = previewCache.out(self.id);
  938. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  939. self.$preview.html(out.content);
  940. self.setCaption(cap);
  941. if (!isEmpty(out.content)) {
  942. self.$container.removeClass('file-input-new');
  943. }
  944. },
  945. initPreviewDeletes: function () {
  946. var self = this, deleteExtraData = self.deleteExtraData || {},
  947. resetProgress = function () {
  948. if (self.$preview.find('.kv-file-remove').length === 0) {
  949. self.reset();
  950. self.initialCaption = '';
  951. }
  952. };
  953. self.$preview.find('.kv-file-remove').each(function () {
  954. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  955. if (isEmpty(vUrl) || vKey === undefined) {
  956. return;
  957. }
  958. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  959. settings, params, index = $frame.data('fileindex'), config, extraData;
  960. index = parseInt(index.replace('init_', ''));
  961. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  962. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  963. if (typeof extraData === "function") {
  964. extraData = extraData();
  965. }
  966. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  967. settings = $.extend({
  968. url: vUrl,
  969. type: 'DELETE',
  970. dataType: 'json',
  971. data: $.extend({key: vKey}, extraData),
  972. beforeSend: function (jqXHR) {
  973. self.ajaxAborted = false;
  974. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  975. if (self.ajaxAborted) {
  976. jqXHR.abort();
  977. } else {
  978. addCss($frame, 'file-uploading');
  979. addCss($el, 'disabled');
  980. }
  981. },
  982. success: function (data, textStatus, jqXHR) {
  983. var n, cap;
  984. if (data === undefined || data.error === undefined) {
  985. previewCache.unset(self.id, index);
  986. n = previewCache.count(self.id);
  987. cap = n > 0 ? self.getMsgSelected(n) : '';
  988. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  989. self.setCaption(cap);
  990. } else {
  991. params.jqXHR = jqXHR;
  992. params.response = data;
  993. self.showError(data.error, params, 'filedeleteerror');
  994. $frame.removeClass('file-uploading');
  995. $el.removeClass('disabled');
  996. resetProgress();
  997. return;
  998. }
  999. $frame.removeClass('file-uploading').addClass('file-deleted');
  1000. $frame.fadeOut('slow', function () {
  1001. self.clearObjects($frame);
  1002. $frame.remove();
  1003. resetProgress();
  1004. if (!n && self.getFileStack().length === 0) {
  1005. self.setCaption('');
  1006. self.reset();
  1007. }
  1008. });
  1009. },
  1010. error: function (jqXHR, textStatus, errorThrown) {
  1011. var errMsg = self.parseError(jqXHR, errorThrown);
  1012. params.jqXHR = jqXHR;
  1013. params.response = {};
  1014. self.showError(errMsg, params, 'filedeleteerror');
  1015. $frame.removeClass('file-uploading');
  1016. resetProgress();
  1017. }
  1018. }, self.ajaxDeleteSettings);
  1019. $el.off('click').on('click', function () {
  1020. $.ajax(settings);
  1021. });
  1022. });
  1023. },
  1024. clearObjects: function ($el) {
  1025. $el.find('video audio').each(function () {
  1026. this.pause();
  1027. $(this).remove();
  1028. });
  1029. $el.find('img object div').each(function () {
  1030. $(this).remove();
  1031. });
  1032. },
  1033. clearFileInput: function () {
  1034. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1035. if (isEmpty($el.val())) {
  1036. return;
  1037. }
  1038. // Fix for IE ver < 11, that does not clear file inputs
  1039. // Requires a sequence of steps to prevent IE crashing but
  1040. // still allow clearing of the file input.
  1041. if (self.isIE9 || self.isIE10) {
  1042. $srcFrm = $el.closest('form');
  1043. $tmpFrm = $(document.createElement('form'));
  1044. $tmpEl = $(document.createElement('div'));
  1045. $el.before($tmpEl);
  1046. if ($srcFrm.length) {
  1047. $srcFrm.after($tmpFrm);
  1048. } else {
  1049. $tmpEl.after($tmpFrm);
  1050. }
  1051. $tmpFrm.append($el).trigger('reset');
  1052. $tmpEl.before($el).remove();
  1053. $tmpFrm.remove();
  1054. } else { // normal input clear behavior for other sane browsers
  1055. $el.val('');
  1056. }
  1057. self.fileInputCleared = true;
  1058. },
  1059. resetUpload: function () {
  1060. var self = this;
  1061. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1062. self.uploadCount = 0;
  1063. self.uploadPercent = 0;
  1064. self.$btnUpload.removeAttr('disabled');
  1065. self.setProgress(0);
  1066. addCss(self.$progress, 'hide');
  1067. self.resetErrors(false);
  1068. self.ajaxAborted = false;
  1069. self.ajaxRequests = [];
  1070. },
  1071. cancel: function () {
  1072. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1073. if (len > 0) {
  1074. for (i = 0; i < len; i += 1) {
  1075. xhr[i].abort();
  1076. }
  1077. }
  1078. self.getThumbs().each(function () {
  1079. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1080. $thumb.removeClass('file-uploading');
  1081. if (self.filestack[ind] !== undefined) {
  1082. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1083. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1084. }
  1085. self.unlock();
  1086. });
  1087. },
  1088. clear: function () {
  1089. var self = this, cap;
  1090. self.$btnUpload.removeAttr('disabled');
  1091. self.resetUpload();
  1092. self.filestack = [];
  1093. self.clearFileInput();
  1094. self.resetErrors(true);
  1095. self.raise('fileclear');
  1096. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1097. self.showFileIcon();
  1098. self.resetPreview();
  1099. self.setEllipsis();
  1100. self.initPreviewDeletes();
  1101. self.$container.removeClass('file-input-new');
  1102. } else {
  1103. self.getThumbs().each(function () {
  1104. self.clearObjects($(this));
  1105. });
  1106. self.$preview.html('');
  1107. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1108. self.setCaption(cap);
  1109. self.setEllipsis();
  1110. self.$caption.attr('title', '');
  1111. addCss(self.$container, 'file-input-new');
  1112. }
  1113. if (self.$container.find('.file-preview-frame').length === 0) {
  1114. if (!self.initCaption()) {
  1115. self.$captionContainer.find('.kv-caption-icon').hide();
  1116. }
  1117. self.setEllipsis();
  1118. }
  1119. self.hideFileIcon();
  1120. self.raise('filecleared');
  1121. self.$captionContainer.focus();
  1122. self.setFileDropZoneTitle();
  1123. },
  1124. resetPreview: function () {
  1125. var self = this, out;
  1126. if (previewCache.count(self.id)) {
  1127. out = previewCache.out(self.id);
  1128. self.$preview.html(out.content);
  1129. self.setCaption(out.caption);
  1130. } else {
  1131. self.$preview.html('');
  1132. self.initCaption();
  1133. }
  1134. },
  1135. reset: function () {
  1136. var self = this;
  1137. self.clear();
  1138. self.resetPreview();
  1139. self.setEllipsis();
  1140. self.$container.find('.fileinput-filename').text('');
  1141. self.raise('filereset');
  1142. if (self.initialPreview.length > 0) {
  1143. self.$container.removeClass('file-input-new');
  1144. }
  1145. self.setFileDropZoneTitle();
  1146. self.filestack = [];
  1147. self.formdata = {};
  1148. },
  1149. disable: function () {
  1150. var self = this;
  1151. self.isDisabled = true;
  1152. self.raise('filedisabled');
  1153. self.$element.attr('disabled', 'disabled');
  1154. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1155. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  1156. self.initDragDrop();
  1157. },
  1158. enable: function () {
  1159. var self = this;
  1160. self.isDisabled = false;
  1161. self.raise('fileenabled');
  1162. self.$element.removeAttr('disabled');
  1163. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1164. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  1165. self.initDragDrop();
  1166. },
  1167. getThumbs: function (css) {
  1168. css = css || '';
  1169. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1170. },
  1171. getExtraData: function () {
  1172. var self = this, data = self.uploadExtraData;
  1173. if (typeof self.uploadExtraData === "function") {
  1174. data = self.uploadExtraData();
  1175. }
  1176. return data;
  1177. },
  1178. uploadExtra: function () {
  1179. var self = this, data = self.getExtraData();
  1180. if (data.length === 0) {
  1181. return;
  1182. }
  1183. $.each(data, function (key, value) {
  1184. self.formdata.append(key, value);
  1185. });
  1186. },
  1187. initXhr: function (xhrobj, factor) {
  1188. var self = this;
  1189. if (xhrobj.upload) {
  1190. xhrobj.upload.addEventListener('progress', function (event) {
  1191. var pct = 0, position = event.loaded || event.position, total = event.total;
  1192. if (event.lengthComputable) {
  1193. pct = Math.ceil(position / total * factor);
  1194. }
  1195. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1196. self.setProgress(self.uploadPercent);
  1197. }, false);
  1198. }
  1199. return xhrobj;
  1200. },
  1201. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  1202. var self = this, settings;
  1203. self.uploadExtra();
  1204. settings = $.extend({
  1205. xhr: function () {
  1206. var xhrobj = $.ajaxSettings.xhr();
  1207. return self.initXhr(xhrobj, 98);
  1208. },
  1209. url: self.uploadUrl,
  1210. type: 'POST',
  1211. dataType: 'json',
  1212. data: self.formdata,
  1213. cache: false,
  1214. processData: false,
  1215. contentType: false,
  1216. beforeSend: fnBefore,
  1217. success: fnSuccess,
  1218. complete: fnComplete,
  1219. error: fnError
  1220. }, self.ajaxSettings);
  1221. self.ajaxRequests.push($.ajax(settings));
  1222. },
  1223. initUploadSuccess: function (out, $thumb, allFiles) {
  1224. var self = this, append, data, index, $newThumb, content, config, tags;
  1225. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1226. return;
  1227. }
  1228. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1229. self.hasInitData = true;
  1230. content = out.initialPreview || [];
  1231. config = out.initialPreviewConfig || [];
  1232. tags = out.initialPreviewThumbTags || [];
  1233. append = out.append === undefined || out.append ? true : false;
  1234. self.overwriteInitial = false;
  1235. if ($thumb !== undefined && !allFiles) {
  1236. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1237. data = previewCache.get(self.id, index, false);
  1238. $newThumb = $(data).hide();
  1239. $thumb.after($newThumb).fadeOut('slow', function () {
  1240. $newThumb.fadeIn('slow').css('display:inline-block');
  1241. self.initPreviewDeletes();
  1242. self.clearFileInput();
  1243. });
  1244. } else {
  1245. if (allFiles) {
  1246. self.uploadCache.content.push(content[0]);
  1247. self.uploadCache.config.push(config[0]);
  1248. self.uploadCache.tags.push(tags[0]);
  1249. self.uploadCache.append = append;
  1250. } else {
  1251. previewCache.set(self.id, content, config, tags, append);
  1252. self.initPreview();
  1253. self.initPreviewDeletes();
  1254. }
  1255. }
  1256. }
  1257. },
  1258. initSuccessThumbs: function () {
  1259. var self = this;
  1260. self.getThumbs('.file-preview-success').each(function(){
  1261. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1262. $remove.removeAttr('disabled').off('click').on('click', function () {
  1263. var out = self.raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1264. if (out === false) {
  1265. return;
  1266. }
  1267. $thumb.fadeOut('slow', function () {
  1268. $thumb.remove();
  1269. if (!self.$preview.find('.file-preview-frame').length) {
  1270. self.reset();
  1271. }
  1272. });
  1273. });
  1274. });
  1275. },
  1276. uploadSingle: function (i, files, allFiles) {
  1277. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1278. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1279. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1280. updateProgress, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1281. resetActions, fnBefore, fnSuccess, fnComplete, fnError, params = {id: previewId, index: i};
  1282. self.formdata = formdata;
  1283. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1284. return;
  1285. }
  1286. chkComplete = function () {
  1287. var $thumbs = self.getThumbs('.file-uploading');
  1288. if ($thumbs.length > 0 || self.fileBatchCompleted) {
  1289. return;
  1290. }
  1291. self.fileBatchCompleted = true;
  1292. setTimeout(function () {
  1293. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.tags,
  1294. self.uploadCache.append);
  1295. if (self.hasInitData) {
  1296. self.initPreview();
  1297. self.initPreviewDeletes();
  1298. }
  1299. self.setProgress(100);
  1300. self.unlock();
  1301. self.clearFileInput();
  1302. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1303. }, 100);
  1304. };
  1305. updateProgress = function () {
  1306. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1307. return;
  1308. }
  1309. self.uploadCount += 1;
  1310. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1311. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1312. self.setProgress(self.uploadPercent);
  1313. self.initPreviewDeletes();
  1314. };
  1315. resetActions = function () {
  1316. $btnUpload.removeAttr('disabled');
  1317. $btnDelete.removeAttr('disabled');
  1318. $thumb.removeClass('file-uploading');
  1319. };
  1320. fnBefore = function (jqXHR) {
  1321. outData = self.getOutData(jqXHR);
  1322. if (!$thumb.hasClass('file-preview-success')) {
  1323. self.setThumbStatus($thumb, 'Loading');
  1324. addCss($thumb, 'file-uploading');
  1325. }
  1326. $btnUpload.attr('disabled', true);
  1327. $btnDelete.attr('disabled', true);
  1328. if (!allFiles) {
  1329. self.lock();
  1330. }
  1331. self.raise('filepreupload', [outData, previewId, i]);
  1332. params = $.extend(params, outData);
  1333. if (self.abort(params)) {
  1334. jqXHR.abort();
  1335. self.setProgress(100);
  1336. }
  1337. };
  1338. fnSuccess = function (data, textStatus, jqXHR) {
  1339. outData = self.getOutData(jqXHR, data);
  1340. params = $.extend(params, outData);
  1341. setTimeout(function () {
  1342. if (data.error === undefined) {
  1343. self.setThumbStatus($thumb, 'Success');
  1344. $btnUpload.hide();
  1345. self.filestack[i] = undefined;
  1346. self.raise('fileuploaded', [outData, previewId, i]);
  1347. self.initUploadSuccess(data, $thumb, allFiles);
  1348. if (!allFiles) {
  1349. self.resetFileStack();
  1350. }
  1351. } else {
  1352. self.setThumbStatus($thumb, 'Error');
  1353. self.showUploadError(data.error, params);
  1354. }
  1355. }, 100);
  1356. };
  1357. fnComplete = function () {
  1358. setTimeout(function () {
  1359. updateProgress();
  1360. resetActions();
  1361. if (!allFiles) {
  1362. self.unlock(false);
  1363. } else {
  1364. chkComplete();
  1365. }
  1366. self.initSuccessThumbs();
  1367. }, 100);
  1368. };
  1369. fnError = function (jqXHR, textStatus, errorThrown) {
  1370. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1371. self.setThumbStatus($thumb, 'Error');
  1372. params = $.extend(params, self.getOutData(jqXHR));
  1373. self.showUploadError(errMsg, params);
  1374. };
  1375. formdata.append(self.uploadFileAttr, files[i]);
  1376. formdata.append('file_id', i);
  1377. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1378. },
  1379. uploadBatch: function () {
  1380. var self = this, files = self.filestack, total = files.length, config,
  1381. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1382. setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1383. params = {};
  1384. self.formdata = new FormData();
  1385. if (total === 0 || !hasPostData || self.abort(params)) {
  1386. return;
  1387. }
  1388. setAllUploaded = function () {
  1389. $.each(files, function (key) {
  1390. self.filestack[key] = undefined;
  1391. });
  1392. self.clearFileInput();
  1393. };
  1394. fnBefore = function (jqXHR) {
  1395. self.lock();
  1396. var outData = self.getOutData(jqXHR);
  1397. if (self.showPreview) {
  1398. self.getThumbs().each(function () {
  1399. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1400. $btnDelete = $thumb.find('.kv-file-remove');
  1401. if (!$thumb.hasClass('file-preview-success')) {
  1402. self.setThumbStatus($thumb, 'Loading');
  1403. addCss($thumb, 'file-uploading');
  1404. }
  1405. $btnUpload.attr('disabled', true);
  1406. $btnDelete.attr('disabled', true);
  1407. });
  1408. }
  1409. self.raise('filebatchpreupload', [outData]);
  1410. if (self.abort(outData)) {
  1411. jqXHR.abort();
  1412. }
  1413. };
  1414. fnSuccess = function (data, textStatus, jqXHR) {
  1415. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(),
  1416. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1417. if (data.error === undefined || isEmpty(data.error)) {
  1418. self.raise('filebatchuploadsuccess', [outData]);
  1419. setAllUploaded();
  1420. if (self.showPreview) {
  1421. $thumbs.each(function () {
  1422. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1423. $thumb.find('.kv-file-upload').hide();
  1424. self.setThumbStatus($thumb, 'Success');
  1425. $thumb.removeClass('file-uploading');
  1426. $btnUpload.removeAttr('disabled');
  1427. });
  1428. self.initUploadSuccess(data);
  1429. } else {
  1430. self.reset();
  1431. }
  1432. } else {
  1433. if (self.showPreview) {
  1434. $thumbs.each(function () {
  1435. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1436. $btnUpload = $thumb.find('.kv-file-upload');
  1437. $thumb.removeClass('file-uploading');
  1438. $btnUpload.removeAttr('disabled');
  1439. $btnDelete.removeAttr('disabled');
  1440. if (keys.length === 0) {
  1441. self.setThumbStatus($thumb, 'Error');
  1442. return;
  1443. }
  1444. if ($.inArray(key, keys) !== -1) {
  1445. self.setThumbStatus($thumb, 'Error');
  1446. } else {
  1447. $thumb.find('.kv-file-upload').hide();
  1448. self.setThumbStatus($thumb, 'Success');
  1449. self.filestack[key] = undefined;
  1450. }
  1451. });
  1452. self.initUploadSuccess(data);
  1453. }
  1454. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1455. }
  1456. };
  1457. fnComplete = function () {
  1458. self.setProgress(100);
  1459. self.unlock();
  1460. self.initSuccessThumbs();
  1461. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1462. self.clearFileInput();
  1463. };
  1464. fnError = function (jqXHR, textStatus, errorThrown) {
  1465. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1466. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1467. self.uploadFileCount = total - 1;
  1468. if (!self.showPreview) {
  1469. return;
  1470. }
  1471. self.getThumbs().each(function () {
  1472. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1473. $thumb.removeClass('file-uploading');
  1474. if (self.filestack[key] !== undefined) {
  1475. self.setThumbStatus($thumb, 'Error');
  1476. }
  1477. });
  1478. self.getThumbs().removeClass('file-uploading');
  1479. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1480. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1481. };
  1482. $.each(files, function (key, data) {
  1483. if (!isEmpty(files[key])) {
  1484. self.formdata.append(self.uploadFileAttr, data);
  1485. }
  1486. });
  1487. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1488. },
  1489. uploadExtraOnly: function () {
  1490. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1491. self.formdata = new FormData();
  1492. if (self.abort(params)) {
  1493. return;
  1494. }
  1495. fnBefore = function (jqXHR) {
  1496. self.lock();
  1497. var outData = self.getOutData(jqXHR);
  1498. self.raise('filebatchpreupload', [outData]);
  1499. self.setProgress(50);
  1500. params.data = outData;
  1501. params.xhr = jqXHR;
  1502. if (self.abort(params)) {
  1503. jqXHR.abort();
  1504. self.setProgress(100);
  1505. }
  1506. };
  1507. fnSuccess = function (data, textStatus, jqXHR) {
  1508. var outData = self.getOutData(jqXHR, data);
  1509. if (data.error === undefined || isEmpty(data.error)) {
  1510. self.raise('filebatchuploadsuccess', [outData]);
  1511. self.clearFileInput();
  1512. self.initUploadSuccess(data);
  1513. } else {
  1514. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1515. }
  1516. };
  1517. fnComplete = function () {
  1518. self.setProgress(100);
  1519. self.unlock();
  1520. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1521. self.clearFileInput();
  1522. };
  1523. fnError = function (jqXHR, textStatus, errorThrown) {
  1524. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1525. params.data = outData;
  1526. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1527. };
  1528. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1529. },
  1530. hideFileIcon: function () {
  1531. if (this.overwriteInitial) {
  1532. this.$captionContainer.find('.kv-caption-icon').hide();
  1533. }
  1534. },
  1535. showFileIcon: function () {
  1536. this.$captionContainer.find('.kv-caption-icon').show();
  1537. },
  1538. resetErrors: function (fade) {
  1539. var self = this, $error = self.$errorContainer;
  1540. self.isError = false;
  1541. self.$container.removeClass('has-error');
  1542. $error.html('');
  1543. if (fade) {
  1544. $error.fadeOut('slow');
  1545. } else {
  1546. $error.hide();
  1547. }
  1548. },
  1549. showFolderError: function (folders) {
  1550. var self = this, $error = self.$errorContainer;
  1551. if (!folders) {
  1552. return;
  1553. }
  1554. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1555. $error.fadeIn(800);
  1556. addCss(self.$container, 'has-error');
  1557. self.raise('filefoldererror', [folders]);
  1558. },
  1559. showUploadError: function (msg, params, event) {
  1560. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1561. if ($error.find('ul').length === 0) {
  1562. $error.html('<ul><li>' + msg + '</li></ul>');
  1563. } else {
  1564. $error.find('ul').append('<li>' + msg + '</li>');
  1565. }
  1566. $error.fadeIn(800);
  1567. self.raise(ev, [params]);
  1568. addCss(self.$container, 'has-error');
  1569. return true;
  1570. },
  1571. showError: function (msg, params, event) {
  1572. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1573. params = params || {};
  1574. params.reader = self.reader;
  1575. $error.html(msg);
  1576. $error.fadeIn(800);
  1577. self.raise(ev, [params]);
  1578. if (!self.isUploadable) {
  1579. self.clearFileInput();
  1580. }
  1581. addCss(self.$container, 'has-error');
  1582. self.$btnUpload.attr('disabled', true);
  1583. return true;
  1584. },
  1585. errorHandler: function (evt, caption) {
  1586. var self = this, err = evt.target.error;
  1587. switch (err.code) {
  1588. case err.NOT_FOUND_ERR:
  1589. self.showError(self.msgFileNotFound.repl('{name}', caption));
  1590. break;
  1591. case err.SECURITY_ERR:
  1592. self.showError(self.msgFileSecured.repl('{name}', caption));
  1593. break;
  1594. case err.NOT_READABLE_ERR:
  1595. self.showError(self.msgFileNotReadable.repl('{name}', caption));
  1596. break;
  1597. case err.ABORT_ERR:
  1598. self.showError(self.msgFilePreviewAborted.repl('{name}', caption));
  1599. break;
  1600. default:
  1601. self.showError(self.msgFilePreviewError.repl('{name}', caption));
  1602. }
  1603. },
  1604. parseFileType: function (file) {
  1605. var self = this, isValid, vType, cat, i;
  1606. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1607. cat = defaultPreviewTypes[i];
  1608. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1609. vType = isValid(file.type, file.name) ? cat : '';
  1610. if (!isEmpty(vType)) {
  1611. return vType;
  1612. }
  1613. }
  1614. return 'other';
  1615. },
  1616. previewDefault: function (file, previewId, isDisabled) {
  1617. if (!this.showPreview) {
  1618. return;
  1619. }
  1620. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1621. config = self.previewSettings.other,
  1622. footer = self.renderFileFooter(file.name, config.width),
  1623. previewOtherTemplate = self.getPreviewTemplate('other'),
  1624. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1625. frameClass = '';
  1626. if (isDisabled === true) {
  1627. frameClass = ' btn disabled';
  1628. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1629. }
  1630. self.$preview.append("\n" + previewOtherTemplate
  1631. .repl('{previewId}', previewId)
  1632. .repl('{frameClass}', frameClass)
  1633. .repl('{fileindex}', ind)
  1634. .repl('{caption}', self.slug(file.name))
  1635. .repl('{width}', config.width)
  1636. .repl('{height}', config.height)
  1637. .repl('{type}', file.type)
  1638. .repl('{data}', data)
  1639. .repl('{footer}', footer));
  1640. $obj.on('load', function () {
  1641. objUrl.revokeObjectURL($obj.attr('data'));
  1642. });
  1643. },
  1644. previewFile: function (file, theFile, previewId, data) {
  1645. if (!this.showPreview) {
  1646. return;
  1647. }
  1648. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1649. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1650. tmplt = self.getPreviewTemplate(cat),
  1651. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1652. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1653. chkTypes = types.indexOf(cat) >= 0, id, height,
  1654. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && mimes.indexOf(file.type) !== -1),
  1655. footer = self.renderFileFooter(caption, config.width), modal = '',
  1656. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1657. if (chkTypes && chkMimes) {
  1658. if (cat === 'text') {
  1659. strText = htmlEncode(theFile.target.result);
  1660. objUrl.revokeObjectURL(data);
  1661. if (strText.length > wrapLen) {
  1662. id = 'text-' + uniqId();
  1663. height = window.innerHeight * 0.75;
  1664. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1665. .repl('{title}', caption)
  1666. .repl('{height}', height)
  1667. .repl('{body}', strText);
  1668. wrapInd = wrapInd
  1669. .repl('{title}', caption)
  1670. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1671. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1672. }
  1673. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1674. .repl('{frameClass}', '')
  1675. .repl('{type}', file.type).repl('{width}', config.width)
  1676. .repl('{height}', config.height).repl('{data}', strText)
  1677. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1678. } else {
  1679. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1680. .repl('{frameClass}', '')
  1681. .repl('{type}', file.type).repl('{data}', data)
  1682. .repl('{width}', config.width).repl('{height}', config.height)
  1683. .repl('{footer}', footer).repl('{fileindex}', ind);
  1684. }
  1685. self.$preview.append("\n" + content);
  1686. self.autoSizeImage(previewId);
  1687. } else {
  1688. self.previewDefault(file, previewId);
  1689. }
  1690. },
  1691. slugDefault: function (text) {
  1692. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1693. },
  1694. getFileStack: function () {
  1695. var self = this;
  1696. return self.filestack.filter(function (n) {
  1697. return n !== undefined;
  1698. });
  1699. },
  1700. readFiles: function (files) {
  1701. this.reader = new FileReader();
  1702. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1703. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1704. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1705. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1706. throwError = function (msg, file, previewId, index) {
  1707. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1708. p2 = {id: previewId, index: index, file: file, files: files};
  1709. self.previewDefault(file, previewId, true);
  1710. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1711. };
  1712. function readFile(i) {
  1713. if (isEmpty($el.attr('multiple'))) {
  1714. numFiles = 1;
  1715. }
  1716. if (i >= numFiles) {
  1717. if (self.isUploadable && self.filestack.length > 0) {
  1718. self.raise('filebatchselected', [self.getFileStack()]);
  1719. } else {
  1720. self.raise('filebatchselected', [files]);
  1721. }
  1722. $container.removeClass('loading');
  1723. $status.html('');
  1724. return;
  1725. }
  1726. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1727. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1728. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1729. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1730. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1731. if (!isEmpty(fileExt)) {
  1732. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1733. }
  1734. fileSize = fileSize.toFixed(2);
  1735. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1736. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1737. .repl('{size}', fileSize)
  1738. .repl('{maxSize}', self.maxFileSize);
  1739. self.isError = throwError(msg, file, previewId, i);
  1740. return;
  1741. }
  1742. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1743. for (j = 0; j < fileTypes.length; j += 1) {
  1744. typ = fileTypes[j];
  1745. checkFile = settings[typ];
  1746. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1747. fileCount += isEmpty(chk) ? 0 : chk.length;
  1748. }
  1749. if (fileCount === 0) {
  1750. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1751. self.isError = throwError(msg, file, previewId, i);
  1752. return;
  1753. }
  1754. }
  1755. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1756. chk = caption.match(fileExtExpr);
  1757. fileCount += isEmpty(chk) ? 0 : chk.length;
  1758. if (fileCount === 0) {
  1759. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1760. strExt);
  1761. self.isError = throwError(msg, file, previewId, i);
  1762. return;
  1763. }
  1764. }
  1765. if (!self.showPreview) {
  1766. self.filestack.push(file);
  1767. setTimeout(readFile(i + 1), 100);
  1768. self.raise('fileloaded', [file, previewId, i, reader]);
  1769. return;
  1770. }
  1771. if ($preview.length > 0 && FileReader !== undefined) {
  1772. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1773. $container.addClass('loading');
  1774. reader.onerror = function (evt) {
  1775. self.errorHandler(evt, caption);
  1776. };
  1777. reader.onload = function (theFile) {
  1778. self.previewFile(file, theFile, previewId, previewData);
  1779. self.initFileActions();
  1780. };
  1781. reader.onloadend = function () {
  1782. msg = msgProgress
  1783. .repl('{index}', i + 1).repl('{files}', numFiles)
  1784. .repl('{percent}', 50).repl('{name}', caption);
  1785. setTimeout(function () {
  1786. $status.html(msg);
  1787. objUrl.revokeObjectURL(previewData);
  1788. }, 100);
  1789. setTimeout(function () {
  1790. readFile(i + 1);
  1791. self.updateFileDetails(numFiles);
  1792. }, 100);
  1793. self.raise('fileloaded', [file, previewId, i, reader]);
  1794. };
  1795. reader.onprogress = function (data) {
  1796. if (data.lengthComputable) {
  1797. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1798. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1799. .repl('{percent}', progress).repl('{name}', caption);
  1800. setTimeout(function () {
  1801. $status.html(msg);
  1802. }, 100);
  1803. }
  1804. };
  1805. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1806. if (isText(file.type, caption)) {
  1807. reader.readAsText(file, self.textEncoding);
  1808. } else {
  1809. reader.readAsArrayBuffer(file);
  1810. }
  1811. } else {
  1812. self.previewDefault(file, previewId);
  1813. setTimeout(function () {
  1814. readFile(i + 1);
  1815. self.updateFileDetails(numFiles);
  1816. }, 100);
  1817. self.raise('fileloaded', [file, previewId, i, reader]);
  1818. }
  1819. self.filestack.push(file);
  1820. }
  1821. readFile(0);
  1822. self.updateFileDetails(numFiles, false);
  1823. },
  1824. updateFileDetails: function (numFiles) {
  1825. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  1826. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1827. n = self.isUploadable ? fileStack.length : numFiles,
  1828. nFiles = previewCache.count(self.id) + n,
  1829. log = n > 1 ? self.getMsgSelected(nFiles) : label;
  1830. if (self.isError) {
  1831. self.$previewContainer.removeClass('loading');
  1832. self.$previewStatus.html('');
  1833. self.$captionContainer.find('.kv-caption-icon').hide();
  1834. } else {
  1835. self.showFileIcon();
  1836. }
  1837. self.setCaption(log, self.isError);
  1838. self.$container.removeClass('file-input-new file-input-ajax-new');
  1839. if (arguments.length === 1) {
  1840. self.raise('fileselect', [numFiles, label]);
  1841. }
  1842. if (previewCache.count(self.id)) {
  1843. self.initPreviewDeletes();
  1844. }
  1845. },
  1846. change: function (e) {
  1847. var self = this, $el = self.$element;
  1848. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1849. self.fileInputCleared = false;
  1850. return;
  1851. }
  1852. self.fileInputCleared = false;
  1853. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1854. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1855. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1856. ctr = self.filestack.length, isAjaxUpload = self.isUploadable,
  1857. throwError = function (mesg, file, previewId, index) {
  1858. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1859. p2 = {id: previewId, index: index, file: file, files: files};
  1860. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1861. };
  1862. self.reader = null;
  1863. self.resetUpload();
  1864. self.hideFileIcon();
  1865. if (self.isUploadable) {
  1866. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1867. }
  1868. if (isDragDrop) {
  1869. tfiles = [];
  1870. while (files[i]) {
  1871. f = files[i];
  1872. if (!f.type && f.size % 4096 === 0) {
  1873. folders++;
  1874. } else {
  1875. tfiles.push(f);
  1876. }
  1877. i++;
  1878. }
  1879. } else {
  1880. if (e.target.files === undefined) {
  1881. tfiles = e.target && e.target.value ? [
  1882. {name: e.target.value.replace(/^.+\\/, '')}
  1883. ] : [];
  1884. } else {
  1885. tfiles = e.target.files;
  1886. }
  1887. }
  1888. if (isEmpty(tfiles) || tfiles.length === 0) {
  1889. if (!isAjaxUpload) {
  1890. self.clear();
  1891. }
  1892. self.showFolderError(folders);
  1893. self.raise('fileselectnone');
  1894. return;
  1895. }
  1896. self.resetErrors();
  1897. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1898. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1899. msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total);
  1900. self.isError = throwError(msg, null, null, null);
  1901. self.$captionContainer.find('.kv-caption-icon').hide();
  1902. self.$caption.html(self.msgValidationError);
  1903. self.setEllipsis();
  1904. self.$container.removeClass('file-input-new file-input-ajax-new');
  1905. return;
  1906. }
  1907. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1908. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1909. var out = previewCache.out(self.id);
  1910. $preview.html(out.content);
  1911. self.setCaption(out.caption);
  1912. self.initPreviewDeletes();
  1913. } else {
  1914. self.clearPreview();
  1915. }
  1916. if (isSingleUpload && ctr > 0) {
  1917. self.filestack = [];
  1918. }
  1919. } else {
  1920. if (isAjaxUpload && self.overwriteInitial) {
  1921. self.clearPreview();
  1922. self.filestack = [];
  1923. }
  1924. }
  1925. if (!self.isIE9) {
  1926. self.readFiles(tfiles);
  1927. } else {
  1928. self.updateFileDetails(1);
  1929. }
  1930. self.showFolderError(folders);
  1931. },
  1932. autoSizeImage: function (previewId) {
  1933. var self = this, $preview = self.$preview,
  1934. $thumb = $preview.find("#" + previewId),
  1935. $img = $thumb.find('img'), w1, w2, $cap;
  1936. if (!$img.length) {
  1937. return;
  1938. }
  1939. $img.on('load', function () {
  1940. w1 = $thumb.width();
  1941. w2 = $preview.width();
  1942. if (w1 > w2) {
  1943. $img.css('width', '100%');
  1944. $thumb.css('width', '97%');
  1945. }
  1946. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1947. if ($cap.length) {
  1948. $cap.width($img.width());
  1949. $cap.attr('title', $cap.text());
  1950. }
  1951. self.raise('fileimageloaded', previewId);
  1952. });
  1953. },
  1954. initCaption: function () {
  1955. var self = this, cap = self.initialCaption || '';
  1956. if (self.overwriteInitial || isEmpty(cap)) {
  1957. self.$caption.html('');
  1958. return false;
  1959. }
  1960. self.setCaption(cap);
  1961. return true;
  1962. },
  1963. setCaption: function (content, isError) {
  1964. var self = this, err = isError || false, title, out;
  1965. if (err) {
  1966. title = $('<div>' + self.msgValidationError + '</div>').text();
  1967. out = '<span class="' + self.msgValidationErrorClass + '">' +
  1968. self.msgValidationErrorIcon + title + '</span>';
  1969. } else {
  1970. if (isEmpty(content) || self.$caption.length === 0) {
  1971. return;
  1972. }
  1973. title = $('<div>' + content + '</div>').text();
  1974. out = self.getLayoutTemplate('icon') + title;
  1975. }
  1976. self.$caption.html(out);
  1977. self.$caption.attr('title', title);
  1978. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1979. self.setEllipsis();
  1980. },
  1981. initBrowse: function ($container) {
  1982. var self = this;
  1983. self.$btnFile = $container.find('.btn-file');
  1984. self.$btnFile.append(self.$element);
  1985. },
  1986. createContainer: function () {
  1987. var self = this,
  1988. $container = $(document.createElement("span"))
  1989. .attr({"class": 'file-input file-input-new'})
  1990. .html(self.renderMain());
  1991. self.$element.before($container);
  1992. self.initBrowse($container);
  1993. return $container;
  1994. },
  1995. refreshContainer: function () {
  1996. var self = this, $container = self.$container;
  1997. $container.before(self.$element);
  1998. $container.html(self.renderMain());
  1999. self.initBrowse($container);
  2000. },
  2001. renderMain: function () {
  2002. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  2003. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  2004. .repl('{dropClass}', dropCss) : '',
  2005. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2006. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  2007. return self.mainTemplate.repl('{class}', self.mainClass)
  2008. .repl('{preview}', preview)
  2009. .repl('{caption}', caption)
  2010. .repl('{upload}', self.renderUpload())
  2011. .repl('{remove}', self.renderRemove())
  2012. .repl('{cancel}', self.renderCancel())
  2013. .repl('{browse}', self.renderBrowse());
  2014. },
  2015. renderBrowse: function () {
  2016. var self = this, css = self.browseClass + ' btn-file', status = '';
  2017. if (self.isDisabled) {
  2018. status = ' disabled ';
  2019. }
  2020. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  2021. },
  2022. renderRemove: function () {
  2023. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  2024. if (!self.showRemove) {
  2025. return '';
  2026. }
  2027. if (self.isDisabled) {
  2028. status = ' disabled ';
  2029. }
  2030. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  2031. },
  2032. renderCancel: function () {
  2033. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  2034. if (!self.showCancel) {
  2035. return '';
  2036. }
  2037. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  2038. },
  2039. renderUpload: function () {
  2040. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  2041. if (!self.showUpload) {
  2042. return '';
  2043. }
  2044. if (self.isDisabled) {
  2045. status = ' disabled ';
  2046. }
  2047. if (!self.isUploadable || self.isDisabled) {
  2048. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  2049. } else {
  2050. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  2051. }
  2052. return content;
  2053. }
  2054. };
  2055. //FileInput plugin definition
  2056. $.fn.fileinput = function (option) {
  2057. if (!hasFileAPISupport() && !isIE(9)) {
  2058. return;
  2059. }
  2060. var args = Array.apply(null, arguments);
  2061. args.shift();
  2062. return this.each(function () {
  2063. var $this = $(this), data = $this.data('fileinput'), defaults,
  2064. options = typeof option === 'object' && option,
  2065. lang = options.language || $this.data('language') || 'en';
  2066. if (!data) {
  2067. defaults = $.extend({}, $.fn.fileinput.defaults);
  2068. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2069. defaults = $.extend(defaults, $.fn.fileinputLocales[lang]);
  2070. }
  2071. data = new FileInput(this, $.extend(defaults, options, $this.data()));
  2072. $this.data('fileinput', data);
  2073. }
  2074. if (typeof option === 'string') {
  2075. data[option].apply(data, args);
  2076. }
  2077. });
  2078. };
  2079. $.fn.fileinput.defaults = {
  2080. language: 'en',
  2081. showCaption: true,
  2082. showPreview: true,
  2083. showRemove: true,
  2084. showUpload: true,
  2085. showCancel: true,
  2086. showUploadedThumbs: true,
  2087. mainClass: '',
  2088. previewClass: '',
  2089. captionClass: '',
  2090. mainTemplate: null,
  2091. initialCaption: '',
  2092. initialPreview: [],
  2093. initialPreviewDelimiter: '*$$*',
  2094. initialPreviewConfig: [],
  2095. initialPreviewThumbTags: [],
  2096. previewThumbTags: {},
  2097. initialPreviewShowDelete: true,
  2098. deleteUrl: '',
  2099. deleteExtraData: {},
  2100. overwriteInitial: true,
  2101. layoutTemplates: defaultLayoutTemplates,
  2102. previewTemplates: defaultPreviewTemplates,
  2103. allowedPreviewTypes: defaultPreviewTypes,
  2104. allowedPreviewMimeTypes: null,
  2105. allowedFileTypes: null,
  2106. allowedFileExtensions: null,
  2107. customLayoutTags: {},
  2108. customPreviewTags: {},
  2109. previewSettings: defaultPreviewSettings,
  2110. fileTypeSettings: defaultFileTypeSettings,
  2111. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2112. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2113. browseClass: 'btn btn-primary',
  2114. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2115. removeClass: 'btn btn-default',
  2116. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2117. cancelClass: 'btn btn-default',
  2118. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2119. uploadClass: 'btn btn-default',
  2120. uploadUrl: null,
  2121. uploadAsync: true,
  2122. uploadExtraData: {},
  2123. maxFileSize: 0,
  2124. minFileCount: 0,
  2125. maxFileCount: 0,
  2126. msgValidationErrorClass: 'text-danger',
  2127. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2128. msgErrorClass: 'file-error-message',
  2129. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2130. progressCompleteClass: "progress-bar progress-bar-success",
  2131. previewFileType: 'image',
  2132. wrapTextLength: 250,
  2133. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2134. elCaptionContainer: null,
  2135. elCaptionText: null,
  2136. elPreviewContainer: null,
  2137. elPreviewImage: null,
  2138. elPreviewStatus: null,
  2139. elErrorContainer: null,
  2140. slugCallback: null,
  2141. dropZoneEnabled: true,
  2142. dropZoneTitleClass: 'file-drop-zone-title',
  2143. fileActionSettings: {},
  2144. otherActionButtons: '',
  2145. textEncoding: 'UTF-8',
  2146. ajaxSettings: {},
  2147. ajaxDeleteSettings: {},
  2148. showAjaxErrorDetails: true
  2149. };
  2150. $.fn.fileinputLocales.en = {
  2151. fileSingle: 'file',
  2152. filePlural: 'files',
  2153. browseLabel: 'Browse &hellip;',
  2154. removeLabel: 'Remove',
  2155. removeTitle: 'Clear selected files',
  2156. cancelLabel: 'Cancel',
  2157. cancelTitle: 'Abort ongoing upload',
  2158. uploadLabel: 'Upload',
  2159. uploadTitle: 'Upload selected files',
  2160. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2161. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2162. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2163. msgFileNotFound: 'File "{name}" not found!',
  2164. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2165. msgFileNotReadable: 'File "{name}" is not readable.',
  2166. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2167. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2168. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2169. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2170. msgValidationError: 'File Upload Error',
  2171. msgLoading: 'Loading file {index} of {files} &hellip;',
  2172. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2173. msgSelected: '{n} {files} selected',
  2174. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2175. dropZoneTitle: 'Drag & drop files here &hellip;'
  2176. };
  2177. $.extend($.fn.fileinput.defaults, $.fn.fileinputLocales.en);
  2178. $.fn.fileinput.Constructor = FileInput;
  2179. /**
  2180. * Convert automatically file inputs with class 'file'
  2181. * into a bootstrap fileinput control.
  2182. */
  2183. $(document).ready(function () {
  2184. var $input = $('input.file[type=file]');
  2185. if ($input.length) {
  2186. $input.fileinput();
  2187. }
  2188. });
  2189. })(window.jQuery);