fileinput.js 109 KB

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