fileinput.js 125 KB

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