fileinput.js 103 KB

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