fileinput.js 104 KB

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