fileinput.js 103 KB

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