fileinput.js 123 KB

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