fileinput.js 122 KB

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