fileinput.js 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.2.8
  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), 'file-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('file-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('file-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.updateStack(i, undefined);
  1530. } else {
  1531. updateUploadLog(i, previewId);
  1532. }
  1533. } else {
  1534. self.setThumbStatus($thumb, 'Error');
  1535. self.showUploadError(data.error, params);
  1536. if (allFiles) {
  1537. updateUploadLog(i, previewId);
  1538. }
  1539. }
  1540. }, 100);
  1541. };
  1542. fnComplete = function () {
  1543. setTimeout(function () {
  1544. if (self.showPreview) {
  1545. $btnUpload.removeAttr('disabled');
  1546. $btnDelete.removeAttr('disabled');
  1547. $thumb.removeClass('file-uploading');
  1548. }
  1549. if (!allFiles) {
  1550. self.unlock(false);
  1551. } else {
  1552. chkComplete();
  1553. }
  1554. self.initSuccessThumbs();
  1555. }, 100);
  1556. };
  1557. fnError = function (jqXHR, textStatus, errorThrown) {
  1558. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1559. setTimeout(function () {
  1560. if (allFiles) {
  1561. updateUploadLog(i, previewId);
  1562. }
  1563. self.uploadStatus[previewId] = 100;
  1564. self.setThumbStatus($thumb, 'Error');
  1565. params = $.extend(params, self.getOutData(jqXHR));
  1566. self.showUploadError(errMsg, params);
  1567. }, 100);
  1568. };
  1569. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1570. formdata.append('file_id', i);
  1571. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1572. },
  1573. uploadBatch: function () {
  1574. var self = this, files = self.filestack, total = files.length, params = {},
  1575. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1576. setAllUploaded, fnBefore, fnSuccess, fnComplete, fnError;
  1577. self.formdata = new FormData();
  1578. if (total === 0 || !hasPostData || self.abort(params)) {
  1579. return;
  1580. }
  1581. setAllUploaded = function () {
  1582. $.each(files, function (key) {
  1583. self.updateStack(key, undefined);
  1584. });
  1585. self.clearFileInput();
  1586. };
  1587. fnBefore = function (jqXHR) {
  1588. self.lock();
  1589. var outData = self.getOutData(jqXHR);
  1590. if (self.showPreview) {
  1591. self.getThumbs().each(function () {
  1592. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1593. $btnDelete = $thumb.find('.kv-file-remove');
  1594. if (!$thumb.hasClass('file-preview-success')) {
  1595. self.setThumbStatus($thumb, 'Loading');
  1596. addCss($thumb, 'file-uploading');
  1597. }
  1598. $btnUpload.attr('disabled', true);
  1599. $btnDelete.attr('disabled', true);
  1600. });
  1601. }
  1602. self.raise('filebatchpreupload', [outData]);
  1603. if (self.abort(outData)) {
  1604. jqXHR.abort();
  1605. self.setProgress(100);
  1606. }
  1607. };
  1608. fnSuccess = function (data, textStatus, jqXHR) {
  1609. /** @namespace data.errorkeys */
  1610. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(), key = 0,
  1611. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1612. if (isEmpty(data) || isEmpty(data.error)) {
  1613. self.raise('filebatchuploadsuccess', [outData]);
  1614. setAllUploaded();
  1615. if (self.showPreview) {
  1616. $thumbs.each(function () {
  1617. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1618. $thumb.find('.kv-file-upload').hide();
  1619. self.setThumbStatus($thumb, 'Success');
  1620. $thumb.removeClass('file-uploading');
  1621. $btnUpload.removeAttr('disabled');
  1622. });
  1623. self.initUploadSuccess(data);
  1624. } else {
  1625. self.reset();
  1626. }
  1627. } else {
  1628. if (self.showPreview) {
  1629. $thumbs.each(function () {
  1630. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1631. $btnUpload = $thumb.find('.kv-file-upload');
  1632. $thumb.removeClass('file-uploading');
  1633. $btnUpload.removeAttr('disabled');
  1634. $btnDelete.removeAttr('disabled');
  1635. if (keys.length === 0) {
  1636. self.setThumbStatus($thumb, 'Error');
  1637. return;
  1638. }
  1639. if ($.inArray(key, keys) !== -1) {
  1640. self.setThumbStatus($thumb, 'Error');
  1641. } else {
  1642. $thumb.find('.kv-file-upload').hide();
  1643. self.setThumbStatus($thumb, 'Success');
  1644. self.updateStack(key, undefined);
  1645. }
  1646. key++;
  1647. });
  1648. self.initUploadSuccess(data);
  1649. }
  1650. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1651. }
  1652. };
  1653. fnComplete = function () {
  1654. self.setProgress(100);
  1655. self.unlock();
  1656. self.initSuccessThumbs();
  1657. self.clearFileInput();
  1658. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1659. };
  1660. fnError = function (jqXHR, textStatus, errorThrown) {
  1661. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1662. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1663. self.uploadFileCount = total - 1;
  1664. if (!self.showPreview) {
  1665. return;
  1666. }
  1667. self.getThumbs().each(function () {
  1668. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1669. $thumb.removeClass('file-uploading');
  1670. if (self.filestack[key] !== undefined) {
  1671. self.setThumbStatus($thumb, 'Error');
  1672. }
  1673. });
  1674. self.getThumbs().removeClass('file-uploading');
  1675. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1676. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1677. };
  1678. $.each(files, function (key, data) {
  1679. if (!isEmpty(files[key])) {
  1680. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  1681. }
  1682. });
  1683. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1684. },
  1685. uploadExtraOnly: function () {
  1686. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1687. self.formdata = new FormData();
  1688. if (self.abort(params)) {
  1689. return;
  1690. }
  1691. fnBefore = function (jqXHR) {
  1692. self.lock();
  1693. var outData = self.getOutData(jqXHR);
  1694. self.raise('filebatchpreupload', [outData]);
  1695. self.setProgress(50);
  1696. params.data = outData;
  1697. params.xhr = jqXHR;
  1698. if (self.abort(params)) {
  1699. jqXHR.abort();
  1700. self.setProgress(100);
  1701. }
  1702. };
  1703. fnSuccess = function (data, textStatus, jqXHR) {
  1704. var outData = self.getOutData(jqXHR, data);
  1705. if (isEmpty(data) || isEmpty(data.error)) {
  1706. self.raise('filebatchuploadsuccess', [outData]);
  1707. self.clearFileInput();
  1708. self.initUploadSuccess(data);
  1709. } else {
  1710. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1711. }
  1712. };
  1713. fnComplete = function () {
  1714. self.setProgress(100);
  1715. self.unlock();
  1716. self.clearFileInput();
  1717. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1718. };
  1719. fnError = function (jqXHR, textStatus, errorThrown) {
  1720. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1721. params.data = outData;
  1722. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1723. };
  1724. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1725. },
  1726. upload: function () {
  1727. var self = this, totLen = self.getFileStack().length, params = {},
  1728. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  1729. if (self.minFileCount > 0 && self.getFileCount(totLen) < self.minFileCount) {
  1730. self.noFilesError(params);
  1731. return;
  1732. }
  1733. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  1734. return;
  1735. }
  1736. self.resetUpload();
  1737. self.$progress.removeClass('hide');
  1738. self.uploadCount = 0;
  1739. self.uploadStatus = {};
  1740. self.uploadLog = [];
  1741. self.lock();
  1742. self.setProgress(2);
  1743. if (totLen === 0 && hasExtraData) {
  1744. self.uploadExtraOnly();
  1745. return;
  1746. }
  1747. len = self.filestack.length;
  1748. self.hasInitData = false;
  1749. if (self.uploadAsync) {
  1750. outData = self.getOutData();
  1751. self.raise('filebatchpreupload', [outData]);
  1752. self.fileBatchCompleted = false;
  1753. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1754. self.uploadAsyncCount = self.getFileStack().length;
  1755. for (i = 0; i < len; i++) {
  1756. self.uploadCache.content[i] = null;
  1757. self.uploadCache.config[i] = null;
  1758. self.uploadCache.tags[i] = null;
  1759. }
  1760. for (i = 0; i < len; i++) {
  1761. if (self.filestack[i] !== undefined) {
  1762. self.uploadSingle(i, self.filestack, true);
  1763. }
  1764. }
  1765. return;
  1766. }
  1767. self.uploadBatch();
  1768. },
  1769. initFileActions: function () {
  1770. var self = this;
  1771. if (!self.showPreview) {
  1772. return;
  1773. }
  1774. self.$preview.find('.kv-file-remove').each(function () {
  1775. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  1776. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  1777. handler($el, 'click', function () {
  1778. status = self.raise('filepreremove', [id, ind]);
  1779. if (status === false || !self.validateMinCount()) {
  1780. return false;
  1781. }
  1782. hasError = $frame.hasClass('file-preview-error');
  1783. self.cleanMemory($frame);
  1784. $frame.fadeOut('slow', function () {
  1785. self.updateStack(ind, undefined);
  1786. self.clearObjects($frame);
  1787. $frame.remove();
  1788. if (id && hasError) {
  1789. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  1790. $(this).remove();
  1791. if (!self.errorsExist()) {
  1792. self.resetErrors();
  1793. }
  1794. });
  1795. }
  1796. var filestack = self.getFileStack(true), len = filestack.length, chk = previewCache.count(self.id),
  1797. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  1798. self.clearFileInput();
  1799. if (len === 0 && chk === 0 && !hasThumb) {
  1800. self.reset();
  1801. } else {
  1802. n = chk + len;
  1803. cap = n > 1 ? self.getMsgSelected(n) : (filestack[0] ? self.getFileNames()[0] : '');
  1804. self.setCaption(cap);
  1805. }
  1806. self.raise('fileremoved', [id, ind]);
  1807. });
  1808. });
  1809. });
  1810. self.$preview.find('.kv-file-upload').each(function () {
  1811. var $el = $(this);
  1812. handler($el, 'click', function () {
  1813. var $frame = $el.closest('.file-preview-frame'),
  1814. ind = $frame.attr('data-fileindex');
  1815. if (!$frame.hasClass('file-preview-error')) {
  1816. self.uploadSingle(ind, self.filestack, false);
  1817. }
  1818. });
  1819. });
  1820. },
  1821. hideFileIcon: function () {
  1822. if (this.overwriteInitial) {
  1823. this.$captionContainer.find('.kv-caption-icon').hide();
  1824. }
  1825. },
  1826. showFileIcon: function () {
  1827. this.$captionContainer.find('.kv-caption-icon').show();
  1828. },
  1829. addError: function (msg) {
  1830. var self = this, $error = self.$errorContainer;
  1831. if (msg && $error.length) {
  1832. $error.html(self.errorCloseButton + msg);
  1833. $error.find('.kv-error-close').off('click').on('click', function () {
  1834. $error.fadeOut('slow');
  1835. });
  1836. }
  1837. },
  1838. resetErrors: function (fade) {
  1839. var self = this, $error = self.$errorContainer;
  1840. self.isError = false;
  1841. self.$container.removeClass('has-error');
  1842. $error.html('');
  1843. if (fade) {
  1844. $error.fadeOut('slow');
  1845. } else {
  1846. $error.hide();
  1847. }
  1848. },
  1849. showFolderError: function (folders) {
  1850. var self = this, $error = self.$errorContainer;
  1851. if (!folders) {
  1852. return;
  1853. }
  1854. self.addError(self.msgFoldersNotAllowed.replace(/\{n}/g, folders));
  1855. $error.fadeIn(800);
  1856. addCss(self.$container, 'has-error');
  1857. self.raise('filefoldererror', [folders]);
  1858. },
  1859. showUploadError: function (msg, params, event) {
  1860. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  1861. e = params && params.id ? '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1862. if ($error.find('ul').length === 0) {
  1863. self.addError('<ul>' + e + '</ul>');
  1864. } else {
  1865. $error.find('ul').append(e);
  1866. }
  1867. $error.fadeIn(800);
  1868. self.raise(ev, [params]);
  1869. self.$container.removeClass('file-input-new');
  1870. addCss(self.$container, 'has-error');
  1871. return true;
  1872. },
  1873. showError: function (msg, params, event) {
  1874. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1875. params = params || {};
  1876. params.reader = self.reader;
  1877. self.addError(msg);
  1878. $error.fadeIn(800);
  1879. self.raise(ev, [params]);
  1880. if (!self.isUploadable) {
  1881. self.clearFileInput();
  1882. }
  1883. self.$container.removeClass('file-input-new');
  1884. addCss(self.$container, 'has-error');
  1885. self.$btnUpload.attr('disabled', true);
  1886. return true;
  1887. },
  1888. errorHandler: function (evt, caption) {
  1889. var self = this, err = evt.target.error;
  1890. /** @namespace err.NOT_FOUND_ERR */
  1891. /** @namespace err.SECURITY_ERR */
  1892. /** @namespace err.NOT_READABLE_ERR */
  1893. if (err.code === err.NOT_FOUND_ERR) {
  1894. self.showError(self.msgFileNotFound.replace('{name}', caption));
  1895. } else if (err.code === err.SECURITY_ERR) {
  1896. self.showError(self.msgFileSecured.replace('{name}', caption));
  1897. } else if (err.code === err.NOT_READABLE_ERR) {
  1898. self.showError(self.msgFileNotReadable.replace('{name}', caption));
  1899. } else if (err.code === err.ABORT_ERR) {
  1900. self.showError(self.msgFilePreviewAborted.replace('{name}', caption));
  1901. } else {
  1902. self.showError(self.msgFilePreviewError.replace('{name}', caption));
  1903. }
  1904. },
  1905. parseFileType: function (file) {
  1906. var self = this, isValid, vType, cat, i;
  1907. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1908. cat = defaultPreviewTypes[i];
  1909. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1910. vType = isValid(file.type, file.name) ? cat : '';
  1911. if (!isEmpty(vType)) {
  1912. return vType;
  1913. }
  1914. }
  1915. return 'other';
  1916. },
  1917. previewDefault: function (file, previewId, isDisabled) {
  1918. if (!this.showPreview) {
  1919. return;
  1920. }
  1921. var self = this, frameClass = '', fname = file ? file.name : '',
  1922. /** @namespace objUrl.createObjectURL */
  1923. data = objUrl.createObjectURL(file), ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1924. config = self.previewSettings.other || defaultPreviewSettings.other,
  1925. footer = self.renderFileFooter(file.name, config.width),
  1926. previewOtherTemplate = self.parseFilePreviewIcon(self.getPreviewTemplate('other'), fname);
  1927. if (isDisabled === true) {
  1928. if (!self.isUploadable) {
  1929. footer += '<div class="file-other-error" title="' + self.fileActionSettings.indicatorErrorTitle +
  1930. '">' + self.fileActionSettings.indicatorError + '</div>';
  1931. }
  1932. }
  1933. self.clearDefaultPreview();
  1934. self.$preview.append("\n" + previewOtherTemplate
  1935. .replace(/\{previewId}/g, previewId)
  1936. .replace(/\{frameClass}/g, frameClass)
  1937. .replace(/\{fileindex}/g, ind)
  1938. .replace(/\{caption}/g, self.slug(file.name))
  1939. .replace(/\{width}/g, config.width)
  1940. .replace(/\{height}/g, config.height)
  1941. .replace(/\{type}/g, file.type)
  1942. .replace(/\{data}/g, data)
  1943. .replace(/\{footer}/g, footer));
  1944. if (isDisabled === true && self.isUploadable) {
  1945. self.setThumbStatus($('#' + previewId), 'Error');
  1946. }
  1947. },
  1948. previewFile: function (i, file, theFile, previewId, data) {
  1949. if (!this.showPreview) {
  1950. return;
  1951. }
  1952. var self = this, cat = self.parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  1953. content, strText, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1954. tmplt = self.getPreviewTemplate(cat), chkTypes = types && types.indexOf(cat) >= 0, id,
  1955. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1956. chkMimes = mimes && mimes.indexOf(file.type) !== -1,
  1957. footer = self.renderFileFooter(caption, config.width), modal = '',
  1958. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1959. if (chkTypes || chkMimes) {
  1960. tmplt = self.parseFilePreviewIcon(tmplt, fname.split('.').pop());
  1961. if (cat === 'text') {
  1962. strText = htmlEncode(theFile.target.result);
  1963. id = 'text-' + uniqId();
  1964. content = tmplt.replace(/\{zoom}/g, self.getLayoutTemplate('zoom'));
  1965. modal = self.getLayoutTemplate('modal').replace('{id}', id)
  1966. .replace(/\{title}/g, caption)
  1967. .replace(/\{body}/g, strText).replace(/\{heading}/g, self.msgZoomModalHeading);
  1968. content = content.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  1969. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  1970. .replace(/\{frameClass}/g, '').replace(/\{zoomInd}/g, self.zoomIndicator)
  1971. .replace(/\{footer}/g, footer).replace(/\{fileindex}/g, ind)
  1972. .replace(/\{type}/g, file.type).replace(/\{zoomTitle}/g, self.msgZoomTitle)
  1973. .replace(/\{dialog}/g, "$('#" + id + "').modal('show')")
  1974. .replace(/\{data}/g, strText) + modal;
  1975. } else {
  1976. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  1977. .replace(/\{frameClass}/g, '').replace(/\{type}/g, file.type).replace(/\{fileindex}/g, ind)
  1978. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  1979. .replace(/\{footer}/g, footer).replace(/\{data}/g, data);
  1980. }
  1981. self.clearDefaultPreview();
  1982. self.$preview.append("\n" + content);
  1983. self.validateImage(i, previewId, caption, file.type);
  1984. } else {
  1985. self.previewDefault(file, previewId);
  1986. }
  1987. },
  1988. slugDefault: function (text) {
  1989. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1990. },
  1991. readFiles: function (files) {
  1992. this.reader = new FileReader();
  1993. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1994. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1995. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1996. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  1997. throwError = function (msg, file, previewId, index) {
  1998. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1999. p2 = {id: previewId, index: index, file: file, files: files};
  2000. self.previewDefault(file, previewId, true);
  2001. if (self.isUploadable) {
  2002. self.pushStack(undefined);
  2003. }
  2004. setTimeout(readFile(index + 1), 100);
  2005. self.initFileActions();
  2006. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  2007. };
  2008. self.loadedImages = [];
  2009. self.totalImagesCount = 0;
  2010. $.each(files, function (key, file) {
  2011. var cat = 'image',
  2012. func = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  2013. if (func && func(file.type)) {
  2014. self.totalImagesCount++;
  2015. }
  2016. });
  2017. readFile = function (i) {
  2018. if (isEmpty($el.attr('multiple'))) {
  2019. numFiles = 1;
  2020. }
  2021. if (i >= numFiles) {
  2022. if (self.isUploadable && self.filestack.length > 0) {
  2023. self.raise('filebatchselected', [self.getFileStack()]);
  2024. } else {
  2025. self.raise('filebatchselected', [files]);
  2026. }
  2027. $container.removeClass('file-thumb-loading');
  2028. $status.html('');
  2029. return;
  2030. }
  2031. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  2032. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  2033. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  2034. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  2035. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  2036. if (!isEmpty(fileExt)) {
  2037. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2038. }
  2039. fileSize = fileSize.toFixed(2);
  2040. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2041. msg = self.msgSizeTooLarge.replace('{name}', caption)
  2042. .replace('{size}', fileSize)
  2043. .replace('{maxSize}', self.maxFileSize);
  2044. self.isError = throwError(msg, file, previewId, i);
  2045. return;
  2046. }
  2047. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  2048. for (j = 0; j < fileTypes.length; j += 1) {
  2049. typ = fileTypes[j];
  2050. checkFile = settings[typ];
  2051. chk = (checkFile !== undefined && checkFile(file.type, caption));
  2052. fileCount += isEmpty(chk) ? 0 : chk.length;
  2053. }
  2054. if (fileCount === 0) {
  2055. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2056. self.isError = throwError(msg, file, previewId, i);
  2057. return;
  2058. }
  2059. }
  2060. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  2061. chk = caption.match(fileExtExpr);
  2062. fileCount += isEmpty(chk) ? 0 : chk.length;
  2063. if (fileCount === 0) {
  2064. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  2065. strExt);
  2066. self.isError = throwError(msg, file, previewId, i);
  2067. return;
  2068. }
  2069. }
  2070. if (!self.showPreview) {
  2071. self.pushStack(file);
  2072. setTimeout(readFile(i + 1), 100);
  2073. self.raise('fileloaded', [file, previewId, i, reader]);
  2074. return;
  2075. }
  2076. if ($preview.length > 0 && FileReader !== undefined) {
  2077. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2078. $container.addClass('file-thumb-loading');
  2079. reader.onerror = function (evt) {
  2080. self.errorHandler(evt, caption);
  2081. };
  2082. reader.onload = function (theFile) {
  2083. self.previewFile(i, file, theFile, previewId, previewData);
  2084. self.initFileActions();
  2085. };
  2086. reader.onloadend = function () {
  2087. msg = msgProgress
  2088. .replace('{index}', i + 1).replace('{files}', numFiles)
  2089. .replace('{percent}', 50).replace('{name}', caption);
  2090. setTimeout(function () {
  2091. $status.html(msg);
  2092. self.updateFileDetails(numFiles);
  2093. readFile(i + 1);
  2094. }, 100);
  2095. self.raise('fileloaded', [file, previewId, i, reader]);
  2096. };
  2097. reader.onprogress = function (data) {
  2098. if (data.lengthComputable) {
  2099. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2100. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2101. .replace('{percent}', progress).replace('{name}', caption);
  2102. setTimeout(function () {
  2103. $status.html(msg);
  2104. }, 100);
  2105. }
  2106. };
  2107. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  2108. if (isText(file.type, caption)) {
  2109. reader.readAsText(file, self.textEncoding);
  2110. } else {
  2111. reader.readAsArrayBuffer(file);
  2112. }
  2113. } else {
  2114. self.previewDefault(file, previewId);
  2115. setTimeout(function () {
  2116. readFile(i + 1);
  2117. self.updateFileDetails(numFiles);
  2118. }, 100);
  2119. self.raise('fileloaded', [file, previewId, i, reader]);
  2120. }
  2121. self.pushStack(file);
  2122. };
  2123. readFile(0);
  2124. self.updateFileDetails(numFiles, false);
  2125. },
  2126. updateFileDetails: function (numFiles) {
  2127. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2128. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  2129. n = self.isUploadable ? fileStack.length : numFiles,
  2130. nFiles = previewCache.count(self.id) + n,
  2131. log = n > 1 ? self.getMsgSelected(nFiles) : label;
  2132. if (self.isError) {
  2133. self.$previewContainer.removeClass('file-thumb-loading');
  2134. self.$previewStatus.html('');
  2135. self.$captionContainer.find('.kv-caption-icon').hide();
  2136. } else {
  2137. self.showFileIcon();
  2138. }
  2139. self.setCaption(log, self.isError);
  2140. self.$container.removeClass('file-input-new file-input-ajax-new');
  2141. if (arguments.length === 1) {
  2142. self.raise('fileselect', [numFiles, label]);
  2143. }
  2144. if (previewCache.count(self.id)) {
  2145. self.initPreviewDeletes();
  2146. }
  2147. },
  2148. validateMinCount: function () {
  2149. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2150. if (self.validateInitialCount && self.minFileCount > 0 && self.getFileCount(len - 1) < self.minFileCount) {
  2151. self.noFilesError({});
  2152. return false;
  2153. }
  2154. return true;
  2155. },
  2156. getFileCount: function (fileCount) {
  2157. var self = this, addCount = 0;
  2158. if (self.validateInitialCount && !self.overwriteInitial) {
  2159. addCount = previewCache.count(self.id);
  2160. fileCount += addCount;
  2161. }
  2162. return fileCount;
  2163. },
  2164. change: function (e) {
  2165. var self = this, $el = self.$element;
  2166. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2167. self.fileInputCleared = false;
  2168. return;
  2169. }
  2170. self.fileInputCleared = false;
  2171. var tfiles, msg, total, isDragDrop = arguments.length > 1,
  2172. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  2173. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, n, folders = 0,
  2174. ctr = self.filestack.length, isAjaxUpload = self.isUploadable, len,
  2175. flagSingle = (isSingleUpload && ctr > 0),
  2176. throwError = function (mesg, file, previewId, index) {
  2177. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  2178. p2 = {id: previewId, index: index, file: file, files: files};
  2179. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  2180. };
  2181. self.reader = null;
  2182. self.resetUpload();
  2183. self.hideFileIcon();
  2184. if (self.isUploadable) {
  2185. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2186. }
  2187. if (isDragDrop) {
  2188. tfiles = [];
  2189. while (files[i]) {
  2190. f = files[i];
  2191. if (!f.type && f.size % 4096 === 0) {
  2192. folders++;
  2193. } else {
  2194. tfiles.push(f);
  2195. }
  2196. i++;
  2197. }
  2198. } else {
  2199. if (e.target.files === undefined) {
  2200. tfiles = e.target && e.target.value ? [
  2201. {name: e.target.value.replace(/^.+\\/, '')}
  2202. ] : [];
  2203. } else {
  2204. tfiles = e.target.files;
  2205. }
  2206. }
  2207. if (isEmpty(tfiles) || tfiles.length === 0) {
  2208. if (!isAjaxUpload) {
  2209. self.clear();
  2210. }
  2211. self.showFolderError(folders);
  2212. self.raise('fileselectnone');
  2213. return;
  2214. }
  2215. self.resetErrors();
  2216. len = tfiles.length;
  2217. total = self.isUploadable ? self.getFileStack().length + len : len;
  2218. total = self.getFileCount(total);
  2219. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2220. if (!self.autoReplace || len > self.maxFileCount) {
  2221. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2222. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2223. self.isError = throwError(msg, null, null, null);
  2224. self.$captionContainer.find('.kv-caption-icon').hide();
  2225. self.setCaption('', true);
  2226. self.$container.removeClass('file-input-new file-input-ajax-new');
  2227. return;
  2228. }
  2229. if (total > self.maxFileCount) {
  2230. self.resetPreviewThumbs(isAjaxUpload);
  2231. }
  2232. } else {
  2233. if (!isAjaxUpload || flagSingle) {
  2234. self.resetPreviewThumbs(false);
  2235. if (flagSingle) {
  2236. self.clearStack();
  2237. }
  2238. } else {
  2239. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2240. self.resetPreviewThumbs(true);
  2241. }
  2242. }
  2243. }
  2244. if (self.isPreviewable) {
  2245. self.readFiles(tfiles);
  2246. } else {
  2247. self.updateFileDetails(1);
  2248. }
  2249. self.showFolderError(folders);
  2250. },
  2251. getFileName: function (file) {
  2252. return file && file.name ? this.slug(file.name) : undefined;
  2253. },
  2254. getFileNames: function (skipNull) {
  2255. var self = this;
  2256. return self.filenames.filter(function (n) {
  2257. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2258. });
  2259. },
  2260. getFileStack: function (skipNull) {
  2261. var self = this;
  2262. return self.filestack.filter(function (n) {
  2263. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2264. });
  2265. },
  2266. clearStack: function () {
  2267. var self = this;
  2268. self.filestack = [];
  2269. self.filenames = [];
  2270. },
  2271. updateStack: function (i, file) {
  2272. var self = this;
  2273. self.filestack[i] = file;
  2274. self.filenames[i] = self.getFileName(file);
  2275. },
  2276. pushStack: function (file) {
  2277. var self = this;
  2278. self.filestack.push(file);
  2279. self.filenames.push(self.getFileName(file));
  2280. },
  2281. checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2282. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max',
  2283. limit = self[tag + 'Image' + type], $imgEl, isValid;
  2284. if (isEmpty(limit) || !$img.length) {
  2285. return;
  2286. }
  2287. $imgEl = $img[0];
  2288. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2289. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2290. if (isValid) {
  2291. return;
  2292. }
  2293. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2294. self.showUploadError(msg, params);
  2295. self.setThumbStatus($thumb, 'Error');
  2296. self.updateStack(i, null);
  2297. },
  2298. validateImage: function (i, previewId, fname, ftype) {
  2299. var self = this, $preview = self.$preview, params, w1, w2,
  2300. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  2301. fname = fname || 'Untitled';
  2302. if (!$img.length) {
  2303. return;
  2304. }
  2305. handler($img, 'load', function () {
  2306. w1 = $thumb.width();
  2307. w2 = $preview.width();
  2308. if (w1 > w2) {
  2309. $img.css('width', '100%');
  2310. $thumb.css('width', '97%');
  2311. }
  2312. params = {ind: i, id: previewId};
  2313. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2314. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2315. if (!self.resizeImage) {
  2316. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2317. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2318. }
  2319. self.raise('fileimageloaded', [previewId]);
  2320. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2321. self.validateAllImages();
  2322. objUrl.revokeObjectURL($img.attr('src'));
  2323. });
  2324. },
  2325. validateAllImages: function () {
  2326. var self = this, i, config, $img, $thumb, pid, ind, params = {}, errFunc;
  2327. if (self.loadedImages.length !== self.totalImagesCount) {
  2328. return;
  2329. }
  2330. self.raise('fileimagesloaded');
  2331. if (!self.resizeImage) {
  2332. return;
  2333. }
  2334. errFunc = self.isUploadable ? self.showUploadError : self.showError;
  2335. for (i = 0; i < self.loadedImages.length; i++) {
  2336. config = self.loadedImages[i];
  2337. $img = config.img;
  2338. $thumb = config.thumb;
  2339. pid = config.pid;
  2340. ind = config.ind;
  2341. params = {id: pid, 'index': ind};
  2342. if (!self.getResizedImage($img[0], config.typ, pid, ind)) {
  2343. errFunc(self.msgImageResizeError, params, 'fileimageresizeerror');
  2344. self.setThumbStatus($thumb, 'Error');
  2345. self.updateStack(ind, undefined);
  2346. }
  2347. }
  2348. self.raise('fileimagesresized');
  2349. },
  2350. getResizedImage: function (image, type, pid, ind) {
  2351. var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1,
  2352. maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2353. isValidImage = (width && height), chkWidth, chkHeight,
  2354. canvas = self.imageCanvas, context = self.imageCanvasContext;
  2355. if (!isValidImage) {
  2356. return false;
  2357. }
  2358. if (width === maxWidth && height === maxHeight) {
  2359. return true;
  2360. }
  2361. type = type || self.resizeDefaultImageType;
  2362. chkWidth = width > maxWidth;
  2363. chkHeight = height > maxHeight;
  2364. if (self.resizePreference === 'width') {
  2365. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2366. } else {
  2367. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2368. }
  2369. self.resetCanvas();
  2370. width *= ratio;
  2371. height *= ratio;
  2372. canvas.width = width;
  2373. canvas.height = height;
  2374. try {
  2375. context.drawImage(image, 0, 0, width, height);
  2376. canvas.toBlob(function (blob) {
  2377. self.raise('fileimageresized', [pid, ind]);
  2378. self.filestack[ind] = blob;
  2379. }, type, self.resizeQuality);
  2380. return true;
  2381. }
  2382. catch (err) {
  2383. return false;
  2384. }
  2385. },
  2386. initCaption: function () {
  2387. var self = this, cap = self.initialCaption || '';
  2388. if (self.overwriteInitial || isEmpty(cap)) {
  2389. self.$caption.html('');
  2390. return false;
  2391. }
  2392. self.setCaption(cap);
  2393. return true;
  2394. },
  2395. setCaption: function (content, isError) {
  2396. var self = this, title, out;
  2397. if (isError) {
  2398. title = $('<div>' + self.msgValidationError + '</div>').text();
  2399. out = '<span class="' + self.msgValidationErrorClass + '">' +
  2400. self.msgValidationErrorIcon + title + '</span>';
  2401. } else {
  2402. if (isEmpty(content) || self.$caption.length === 0) {
  2403. return;
  2404. }
  2405. title = $('<div>' + content + '</div>').text();
  2406. out = self.getLayoutTemplate('icon') + title;
  2407. }
  2408. self.$caption.html(out);
  2409. self.$caption.attr('title', title);
  2410. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2411. },
  2412. initBrowse: function ($container) {
  2413. var self = this;
  2414. self.$btnFile = $container.find('.btn-file');
  2415. self.$btnFile.append(self.$element);
  2416. },
  2417. createContainer: function () {
  2418. var self = this,
  2419. $container = $(document.createElement("div"))
  2420. .attr({"class": 'file-input file-input-new'})
  2421. .html(self.renderMain());
  2422. self.$element.before($container);
  2423. self.initBrowse($container);
  2424. return $container;
  2425. },
  2426. refreshContainer: function () {
  2427. var self = this, $container = self.$container;
  2428. $container.before(self.$element);
  2429. $container.html(self.renderMain());
  2430. self.initBrowse($container);
  2431. },
  2432. renderMain: function () {
  2433. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2434. close = !self.showClose ? '' : self.getLayoutTemplate('close'),
  2435. preview = !self.showPreview ? '' : self.getLayoutTemplate('preview')
  2436. .replace(/\{class}/g, self.previewClass)
  2437. .replace(/\{dropClass}/g, dropCss),
  2438. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2439. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2440. return self.mainTemplate.replace(/\{class}/g, self.mainClass)
  2441. .replace(/\{preview}/g, preview)
  2442. .replace(/\{close}/g, close)
  2443. .replace(/\{caption}/g, caption)
  2444. .replace(/\{upload}/g, self.renderButton('upload'))
  2445. .replace(/\{remove}/g, self.renderButton('remove'))
  2446. .replace(/\{cancel}/g, self.renderButton('cancel'))
  2447. .replace(/\{browse}/g, self.renderButton('browse'));
  2448. },
  2449. renderButton: function (type) {
  2450. var self = this, tmplt = self.getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2451. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2452. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2453. switch (type) {
  2454. case 'remove':
  2455. if (!self.showRemove) {
  2456. return '';
  2457. }
  2458. break;
  2459. case 'cancel':
  2460. if (!self.showCancel) {
  2461. return '';
  2462. }
  2463. css += ' hide';
  2464. break;
  2465. case 'upload':
  2466. if (!self.showUpload) {
  2467. return '';
  2468. }
  2469. if (self.isUploadable && !self.isDisabled) {
  2470. tmplt = self.getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2471. } else {
  2472. btnType = 'submit';
  2473. }
  2474. break;
  2475. case 'browse':
  2476. tmplt = self.getLayoutTemplate('btnBrowse');
  2477. break;
  2478. default:
  2479. return '';
  2480. }
  2481. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2482. if (!isEmpty(label)) {
  2483. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2484. }
  2485. return tmplt.replace('{type}', btnType)
  2486. .replace('{css}', css)
  2487. .replace('{title}', title)
  2488. .replace('{status}', status)
  2489. .replace('{icon}', icon)
  2490. .replace('{label}', label);
  2491. }
  2492. }
  2493. ;
  2494. //FileInput plugin definition
  2495. $.fn.fileinput = function (option) {
  2496. if (!hasFileAPISupport() && !isIE(9)) {
  2497. return;
  2498. }
  2499. var args = Array.apply(null, arguments), retvals = [];
  2500. args.shift();
  2501. this.each(function () {
  2502. var $this = $(this), data = $this.data('fileinput'), defaults,
  2503. options = typeof option === 'object' && option,
  2504. lang = options.language || $this.data('language') || 'en';
  2505. if (!data) {
  2506. defaults = $.extend({}, $.fn.fileinput.defaults);
  2507. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2508. defaults = $.extend(defaults, $.fn.fileinputLocales[lang]);
  2509. }
  2510. data = new FileInput(this, $.extend(defaults, options, $this.data()));
  2511. $this.data('fileinput', data);
  2512. }
  2513. if (typeof option === 'string') {
  2514. retvals.push(data[option].apply(data, args));
  2515. }
  2516. });
  2517. switch (retvals.length) {
  2518. case 0:
  2519. return this;
  2520. case 1:
  2521. return retvals[0];
  2522. default:
  2523. return retvals;
  2524. }
  2525. };
  2526. $.fn.fileinput.defaults = {
  2527. language: 'en',
  2528. showCaption: true,
  2529. showPreview: true,
  2530. showRemove: true,
  2531. showUpload: true,
  2532. showCancel: true,
  2533. showClose: true,
  2534. showUploadedThumbs: true,
  2535. autoReplace: false,
  2536. mainClass: '',
  2537. previewClass: '',
  2538. captionClass: '',
  2539. mainTemplate: null,
  2540. initialCaption: '',
  2541. initialPreview: [],
  2542. initialPreviewDelimiter: '*$$*',
  2543. initialPreviewConfig: [],
  2544. initialPreviewThumbTags: [],
  2545. previewThumbTags: {},
  2546. initialPreviewShowDelete: true,
  2547. deleteUrl: '',
  2548. deleteExtraData: {},
  2549. overwriteInitial: true,
  2550. layoutTemplates: defaultLayoutTemplates,
  2551. previewTemplates: defaultPreviewTemplates,
  2552. allowedPreviewTypes: defaultPreviewTypes,
  2553. allowedPreviewMimeTypes: null,
  2554. allowedFileTypes: null,
  2555. allowedFileExtensions: null,
  2556. defaultPreviewContent: null,
  2557. customLayoutTags: {},
  2558. customPreviewTags: {},
  2559. previewSettings: defaultPreviewSettings,
  2560. fileTypeSettings: defaultFileTypeSettings,
  2561. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2562. previewFileIconClass: 'file-icon-4x',
  2563. previewFileIconSettings: {},
  2564. previewFileExtSettings: {},
  2565. buttonLabelClass: 'hidden-xs',
  2566. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>',
  2567. browseClass: 'btn btn-primary',
  2568. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  2569. removeClass: 'btn btn-default',
  2570. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  2571. cancelClass: 'btn btn-default',
  2572. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  2573. uploadClass: 'btn btn-default',
  2574. uploadUrl: null,
  2575. uploadAsync: true,
  2576. uploadExtraData: {},
  2577. minImageWidth: null,
  2578. minImageHeight: null,
  2579. maxImageWidth: null,
  2580. maxImageHeight: null,
  2581. resizeImage: false,
  2582. resizePreference: 'width',
  2583. resizeQuality: 0.92,
  2584. resizeDefaultImageType: 'image/jpeg',
  2585. maxFileSize: 0,
  2586. minFileCount: 0,
  2587. maxFileCount: 0,
  2588. validateInitialCount: false,
  2589. msgValidationErrorClass: 'text-danger',
  2590. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2591. msgErrorClass: 'file-error-message',
  2592. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  2593. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2594. progressCompleteClass: "progress-bar progress-bar-success",
  2595. previewFileType: 'image',
  2596. zoomIndicator: '<i class="glyphicon glyphicon-zoom-in"></i>',
  2597. elCaptionContainer: null,
  2598. elCaptionText: null,
  2599. elPreviewContainer: null,
  2600. elPreviewImage: null,
  2601. elPreviewStatus: null,
  2602. elErrorContainer: null,
  2603. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  2604. slugCallback: null,
  2605. dropZoneEnabled: true,
  2606. dropZoneTitleClass: 'file-drop-zone-title',
  2607. fileActionSettings: {},
  2608. otherActionButtons: '',
  2609. textEncoding: 'UTF-8',
  2610. ajaxSettings: {},
  2611. ajaxDeleteSettings: {},
  2612. showAjaxErrorDetails: true
  2613. };
  2614. $.fn.fileinputLocales.en = {
  2615. fileSingle: 'file',
  2616. filePlural: 'files',
  2617. browseLabel: 'Browse &hellip;',
  2618. removeLabel: 'Remove',
  2619. removeTitle: 'Clear selected files',
  2620. cancelLabel: 'Cancel',
  2621. cancelTitle: 'Abort ongoing upload',
  2622. uploadLabel: 'Upload',
  2623. uploadTitle: 'Upload selected files',
  2624. msgZoomTitle: 'View details',
  2625. msgZoomModalHeading: 'Detailed Preview',
  2626. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  2627. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  2628. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  2629. msgFileNotFound: 'File "{name}" not found!',
  2630. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2631. msgFileNotReadable: 'File "{name}" is not readable.',
  2632. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2633. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2634. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2635. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2636. msgUploadAborted: 'The file upload was aborted',
  2637. msgValidationError: 'File Upload Error',
  2638. msgLoading: 'Loading file {index} of {files} &hellip;',
  2639. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2640. msgSelected: '{n} {files} selected',
  2641. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2642. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2643. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2644. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2645. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2646. msgImageResizeError: 'Could not get the image dimensions to resize.',
  2647. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  2648. dropZoneTitle: 'Drag & drop files here &hellip;'
  2649. };
  2650. $.extend($.fn.fileinput.defaults, $.fn.fileinputLocales.en);
  2651. $.fn.fileinput.Constructor = FileInput;
  2652. /**
  2653. * Convert automatically file inputs with class 'file'
  2654. * into a bootstrap fileinput control.
  2655. */
  2656. $(document).ready(function () {
  2657. var $input = $('input.file[type=file]');
  2658. if ($input.length) {
  2659. $input.fileinput();
  2660. }
  2661. });
  2662. })
  2663. (window.jQuery);