fileinput.js 120 KB

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