fileinput.js 109 KB

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