fileinput.js 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287
  1. /*!
  2. * bootstrap-fileinput v4.3.5
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2016, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD 3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. "use strict";
  13. //noinspection JSUnresolvedVariable
  14. if (typeof define === 'function' && define.amd) { // jshint ignore:line
  15. // AMD. Register as an anonymous module.
  16. define(['jquery'], factory); // jshint ignore:line
  17. } else { // noinspection JSUnresolvedVariable
  18. if (typeof module === 'object' && module.exports) { // jshint ignore:line
  19. // Node/CommonJS
  20. // noinspection JSUnresolvedVariable
  21. module.exports = factory(require('jquery')); // jshint ignore:line
  22. } else {
  23. // Browser globals
  24. factory(window.jQuery);
  25. }
  26. }
  27. }(function ($) {
  28. "use strict";
  29. $.fn.fileinputLocales = {};
  30. $.fn.fileinputThemes = {};
  31. var NAMESPACE, MODAL_ID, STYLE_SETTING, OBJECT_PARAMS, DEFAULT_PREVIEW, objUrl, compare, isIE, handler,
  32. previewCache, getNum, hasFileAPISupport, hasDragDropSupport, hasFileUploadSupport, addCss, tMain1, tMain2,
  33. tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse, tModalMain, tModal, tProgress, tSize,
  34. tFooter, tActions, tActionDelete, tActionUpload, tActionZoom, tActionDrag, tTagBef, tTagBef1, tTagBef2, tTagAft,
  35. tGeneric, tHtml, tImage, tText, tVideo, tAudio, tFlash, tObject, tPdf, tOther, defaultFileActionSettings,
  36. defaultLayoutTemplates, defaultPreviewTemplates, defaultPreviewZoomSettings, defaultPreviewTypes, getElement,
  37. defaultPreviewSettings, defaultFileTypeSettings, isEmpty, isArray, ifSet, uniqId, htmlEncode, replaceTags,
  38. cleanMemory, findFileName, checkFullScreen, toggleFullScreen, moveArray, FileInput;
  39. NAMESPACE = '.fileinput';
  40. MODAL_ID = 'kvFileinputModal';
  41. STYLE_SETTING = 'style="width:{width};height:{height};"';
  42. OBJECT_PARAMS = '<param name="controller" value="true" />\n' +
  43. '<param name="allowFullScreen" value="true" />\n' +
  44. '<param name="allowScriptAccess" value="always" />\n' +
  45. '<param name="autoPlay" value="false" />\n' +
  46. '<param name="autoStart" value="false" />\n' +
  47. '<param name="quality" value="high" />\n';
  48. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  49. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  50. '</div>';
  51. //noinspection JSUnresolvedVariable
  52. objUrl = window.URL || window.webkitURL;
  53. compare = function (input, str, exact) {
  54. return input !== undefined && (exact ? input === str : input.match(str));
  55. };
  56. isIE = function (ver) {
  57. // check for IE versions < 11
  58. if (navigator.appName !== 'Microsoft Internet Explorer') {
  59. return false;
  60. }
  61. if (ver === 10) {
  62. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  63. }
  64. var div = document.createElement("div"), status;
  65. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  66. status = div.getElementsByTagName("i").length;
  67. document.body.appendChild(div);
  68. div.parentNode.removeChild(div);
  69. return status;
  70. };
  71. handler = function ($el, event, callback, skipNS) {
  72. var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE;
  73. $el.off(ev).on(ev, callback);
  74. };
  75. previewCache = {
  76. data: {},
  77. init: function (obj) {
  78. var content = obj.initialPreview, id = obj.id;
  79. if (content.length > 0 && !isArray(content)) {
  80. content = content.split(obj.initialPreviewDelimiter);
  81. }
  82. previewCache.data[id] = {
  83. content: content,
  84. config: obj.initialPreviewConfig,
  85. tags: obj.initialPreviewThumbTags,
  86. delimiter: obj.initialPreviewDelimiter,
  87. previewFileType: obj.initialPreviewFileType,
  88. previewAsData: obj.initialPreviewAsData,
  89. template: obj.previewGenericTemplate,
  90. showZoom: obj.fileActionSettings.showZoom,
  91. showDrag: obj.fileActionSettings.showDrag,
  92. getSize: function (size) {
  93. return obj._getSize(size);
  94. },
  95. parseTemplate: function (cat, data, fname, ftype, pId, ftr, ind) {
  96. var fc = ' file-preview-initial';
  97. return obj._generatePreviewTemplate(cat, data, fname, ftype, pId, false, null, fc, ftr, ind);
  98. },
  99. msg: function (n) {
  100. return obj._getMsgSelected(n);
  101. },
  102. initId: obj.previewInitId,
  103. footer: obj._getLayoutTemplate('footer').replace(/\{progress}/g, obj._renderThumbProgress()),
  104. isDelete: obj.initialPreviewShowDelete,
  105. caption: obj.initialCaption,
  106. actions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key) {
  107. return obj._renderFileActions(showUpload, showDelete, showZoom, showDrag, disabled, url, key, true);
  108. }
  109. };
  110. },
  111. fetch: function (id) {
  112. return previewCache.data[id].content.filter(function (n) {
  113. return n !== null;
  114. });
  115. },
  116. count: function (id, all) {
  117. return !!previewCache.data[id] && !!previewCache.data[id].content ?
  118. (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0;
  119. },
  120. get: function (id, i, isDisabled) {
  121. var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i], content = data.content[i],
  122. previewId = data.initId + '-' + ind, out, $tmp, frameClass = ' file-preview-initial', cat, cap, ftr,
  123. ftype, asData = ifSet('previewAsData', config, data.previewAsData);
  124. isDisabled = isDisabled === undefined ? true : isDisabled;
  125. /** @namespace config.frameAttr */
  126. /** @namespace config.frameClass */
  127. /** @namespace config.filetype */
  128. if (!content) {
  129. return '';
  130. }
  131. if (config && config.frameClass) {
  132. frameClass += ' ' + config.frameClass;
  133. }
  134. if (asData) {
  135. cat = data.previewAsData ? ifSet('type', config, data.previewFileType || 'generic') : 'generic';
  136. cap = ifSet('caption', config);
  137. ftr = previewCache.footer(id, i, isDisabled, (config && config.size || null));
  138. ftype = ifSet('filetype', config, cat);
  139. out = data.parseTemplate(cat, content, cap, ftype, previewId, ftr, ind, null);
  140. } else {
  141. out = data.template
  142. .replace(/\{previewId}/g, previewId).replace(/\{frameClass}/g, frameClass)
  143. .replace(/\{fileindex}/g, ind).replace(/\{content}/g, data.content[i])
  144. .replace(/\{template}/g, ifSet('type', config, data.previewFileType))
  145. .replace(/\{footer}/g, previewCache.footer(id, i, isDisabled, (config && config.size || null)));
  146. }
  147. if (data.tags.length && data.tags[i]) {
  148. out = replaceTags(out, data.tags[i]);
  149. }
  150. if (!isEmpty(config) && !isEmpty(config.frameAttr)) {
  151. $tmp = $(document.createElement('div')).html(out);
  152. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  153. out = $tmp.html();
  154. $tmp.remove();
  155. }
  156. return out;
  157. },
  158. add: function (id, content, config, tags, append) {
  159. var data = $.extend(true, {}, previewCache.data[id]), index;
  160. if (!isArray(content)) {
  161. content = content.split(data.delimiter);
  162. }
  163. if (append) {
  164. index = data.content.push(content) - 1;
  165. data.config[index] = config;
  166. data.tags[index] = tags;
  167. } else {
  168. index = content.length - 1;
  169. data.content = content;
  170. data.config = config;
  171. data.tags = tags;
  172. }
  173. previewCache.data[id] = data;
  174. return index;
  175. },
  176. set: function (id, content, config, tags, append) {
  177. var data = $.extend(true, {}, previewCache.data[id]), i, chk;
  178. if (!content || !content.length) {
  179. return;
  180. }
  181. if (!isArray(content)) {
  182. content = content.split(data.delimiter);
  183. }
  184. chk = content.filter(function (n) {
  185. return n !== null;
  186. });
  187. if (!chk.length) {
  188. return;
  189. }
  190. if (data.content === undefined) {
  191. data.content = [];
  192. }
  193. if (data.config === undefined) {
  194. data.config = [];
  195. }
  196. if (data.tags === undefined) {
  197. data.tags = [];
  198. }
  199. if (append) {
  200. for (i = 0; i < content.length; i++) {
  201. if (content[i]) {
  202. data.content.push(content[i]);
  203. }
  204. }
  205. for (i = 0; i < config.length; i++) {
  206. if (config[i]) {
  207. data.config.push(config[i]);
  208. }
  209. }
  210. for (i = 0; i < tags.length; i++) {
  211. if (tags[i]) {
  212. data.tags.push(tags[i]);
  213. }
  214. }
  215. } else {
  216. data.content = content;
  217. data.config = config;
  218. data.tags = tags;
  219. }
  220. previewCache.data[id] = data;
  221. },
  222. unset: function (id, index) {
  223. var chk = previewCache.count(id);
  224. if (!chk) {
  225. return;
  226. }
  227. if (chk === 1) {
  228. previewCache.data[id].content = [];
  229. previewCache.data[id].config = [];
  230. previewCache.data[id].tags = [];
  231. return;
  232. }
  233. previewCache.data[id].content[index] = null;
  234. previewCache.data[id].config[index] = null;
  235. previewCache.data[id].tags[index] = null;
  236. },
  237. out: function (id) {
  238. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true);
  239. if (len === 0) {
  240. return {content: '', caption: ''};
  241. }
  242. for (var i = 0; i < len; i++) {
  243. html += previewCache.get(id, i);
  244. }
  245. caption = data.msg(previewCache.count(id));
  246. return {content: '<div class="file-initial-thumbs">' + html + '</div>', caption: caption};
  247. },
  248. footer: function (id, i, isDisabled, size) {
  249. var data = previewCache.data[id];
  250. isDisabled = isDisabled === undefined ? true : isDisabled;
  251. if (data.config.length === 0 || isEmpty(data.config[i])) {
  252. return '';
  253. }
  254. var config = data.config[i], caption = ifSet('caption', config), width = ifSet('width', config, 'auto'),
  255. url = ifSet('url', config, false), key = ifSet('key', config, null),
  256. showDel = ifSet('showDelete', config, true), showZoom = ifSet('showZoom', config, data.showZoom),
  257. showDrag = ifSet('showDrag', config, data.showDrag), disabled = (url === false) && isDisabled,
  258. actions = data.isDelete ? data.actions(false, showDel, showZoom, showDrag, disabled, url, key) : '',
  259. footer = data.footer.replace(/\{actions}/g, actions);
  260. return footer.replace(/\{caption}/g, caption).replace(/\{size}/g, data.getSize(size))
  261. .replace(/\{width}/g, width).replace(/\{indicator}/g, '').replace(/\{indicatorTitle}/g, '');
  262. }
  263. };
  264. getNum = function (num, def) {
  265. def = def || 0;
  266. if (typeof num === "number") {
  267. return num;
  268. }
  269. if (typeof num === "string") {
  270. num = parseFloat(num);
  271. }
  272. return isNaN(num) ? def : num;
  273. };
  274. hasFileAPISupport = function () {
  275. return !!(window.File && window.FileReader);
  276. };
  277. hasDragDropSupport = function () {
  278. var div = document.createElement('div');
  279. /** @namespace div.draggable */
  280. /** @namespace div.ondragstart */
  281. /** @namespace div.ondrop */
  282. return !isIE(9) && (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  283. };
  284. hasFileUploadSupport = function () {
  285. return hasFileAPISupport() && window.FormData;
  286. };
  287. addCss = function ($el, css) {
  288. $el.removeClass(css).addClass(css);
  289. };
  290. defaultFileActionSettings = {
  291. showRemove: true,
  292. showUpload: true,
  293. showZoom: true,
  294. showDrag: true,
  295. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  296. removeClass: 'btn btn-xs btn-default',
  297. removeTitle: 'Remove file',
  298. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  299. uploadClass: 'btn btn-xs btn-default',
  300. uploadTitle: 'Upload file',
  301. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  302. zoomClass: 'btn btn-xs btn-default',
  303. zoomTitle: 'View Details',
  304. dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>',
  305. dragClass: 'text-info',
  306. dragTitle: 'Move / Rearrange',
  307. dragSettings: {},
  308. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  309. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  310. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  311. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  312. indicatorNewTitle: 'Not uploaded yet',
  313. indicatorSuccessTitle: 'Uploaded',
  314. indicatorErrorTitle: 'Upload Error',
  315. indicatorLoadingTitle: 'Uploading ...'
  316. };
  317. tMain1 = '{preview}\n' +
  318. '<div class="kv-upload-progress hide"></div>\n' +
  319. '<div class="input-group {class}">\n' +
  320. ' {caption}\n' +
  321. ' <div class="input-group-btn">\n' +
  322. ' {remove}\n' +
  323. ' {cancel}\n' +
  324. ' {upload}\n' +
  325. ' {browse}\n' +
  326. ' </div>\n' +
  327. '</div>';
  328. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  329. tPreview = '<div class="file-preview {class}">\n' +
  330. ' {close}' +
  331. ' <div class="{dropClass}">\n' +
  332. ' <div class="file-preview-thumbnails">\n' +
  333. ' </div>\n' +
  334. ' <div class="clearfix"></div>' +
  335. ' <div class="file-preview-status text-center text-success"></div>\n' +
  336. ' <div class="kv-fileinput-error"></div>\n' +
  337. ' </div>\n' +
  338. '</div>';
  339. tClose = '<div class="close fileinput-remove">&times;</div>\n';
  340. tFileIcon = '<i class="glyphicon glyphicon-file kv-caption-icon"></i>';
  341. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  342. ' <div class="file-caption-name"></div>\n' +
  343. '</div>\n';
  344. //noinspection HtmlUnknownAttribute
  345. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</button>';
  346. //noinspection HtmlUnknownAttribute
  347. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  348. //noinspection HtmlUnknownAttribute
  349. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  350. tModalMain = '<div id="' + MODAL_ID + '" class="file-zoom-dialog modal fade" tabindex="-1" aria-labelledby="' +
  351. MODAL_ID + 'Label"></div>';
  352. tModal = '<div class="modal-dialog modal-lg" role="document">\n' +
  353. ' <div class="modal-content">\n' +
  354. ' <div class="modal-header">\n' +
  355. ' <div class="kv-zoom-actions pull-right">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  356. ' <h3 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h3>\n' +
  357. ' </div>\n' +
  358. ' <div class="modal-body">\n' +
  359. ' <div class="floating-buttons"></div>\n' +
  360. ' <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
  361. ' </div>\n' +
  362. ' </div>\n' +
  363. '</div>\n';
  364. tProgress = '<div class="progress">\n' +
  365. ' <div class="{class}" role="progressbar"' +
  366. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  367. ' {percent}%\n' +
  368. ' </div>\n' +
  369. '</div>';
  370. tSize = ' <br><samp>({sizeText})</samp>';
  371. tFooter = '<div class="file-thumbnail-footer">\n' +
  372. ' <div class="file-footer-caption" title="{caption}">{caption}{size}</div>\n' +
  373. ' {progress} {actions}\n' +
  374. '</div>';
  375. tActions = '<div class="file-actions">\n' +
  376. ' <div class="file-footer-buttons">\n' +
  377. ' {upload} {delete} {zoom} {other}' +
  378. ' </div>\n' +
  379. ' {drag}\n' +
  380. ' <div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' +
  381. ' <div class="clearfix"></div>\n' +
  382. '</div>';
  383. //noinspection HtmlUnknownAttribute
  384. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' + 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  385. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  386. '{uploadIcon}</button>';
  387. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" title="{zoomTitle}">{zoomIcon}</button>';
  388. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  389. tTagBef = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  390. ' data-template="{template}"';
  391. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  392. tTagBef2 = tTagBef + ' title="{caption}" ' + STYLE_SETTING + '><div class="kv-file-content">\n';
  393. tTagAft = '</div>{footer}\n</div>\n';
  394. tGeneric = '{content}\n';
  395. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" ' + STYLE_SETTING + '>{data}</div>\n';
  396. tImage = '<img src="{data}" class="kv-preview-data file-preview-image" title="{caption}" alt="{caption}" ' +
  397. STYLE_SETTING + '>\n';
  398. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly ' + STYLE_SETTING +
  399. '>{data}</textarea>\n';
  400. tVideo = '<video class="kv-preview-data" width="{width}" height="{height}" controls>\n' +
  401. '<source src="{data}" type="{type}">\n' + DEFAULT_PREVIEW + '\n</video>\n';
  402. tAudio = '<audio class="kv-preview-data" controls>\n<source src="' + '{data}' + '" type="{type}">\n' +
  403. DEFAULT_PREVIEW + '\n</audio>\n';
  404. tFlash = '<object class="kv-preview-data file-object" type="application/x-shockwave-flash" ' +
  405. 'width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n';
  406. tObject = '<object class="kv-preview-data file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  407. '<param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n';
  408. tPdf = '<embed class="kv-preview-data" src="{data}" width="{width}" height="{height}" type="application/pdf">\n';
  409. tOther = '<div class="kv-preview-data file-preview-other-frame">\n' + DEFAULT_PREVIEW + '\n</div>\n';
  410. defaultLayoutTemplates = {
  411. main1: tMain1,
  412. main2: tMain2,
  413. preview: tPreview,
  414. close: tClose,
  415. fileIcon: tFileIcon,
  416. caption: tCaption,
  417. modalMain: tModalMain,
  418. modal: tModal,
  419. progress: tProgress,
  420. size: tSize,
  421. footer: tFooter,
  422. actions: tActions,
  423. actionDelete: tActionDelete,
  424. actionUpload: tActionUpload,
  425. actionZoom: tActionZoom,
  426. actionDrag: tActionDrag,
  427. btnDefault: tBtnDefault,
  428. btnLink: tBtnLink,
  429. btnBrowse: tBtnBrowse
  430. };
  431. defaultPreviewTemplates = {
  432. generic: tTagBef1 + tGeneric + tTagAft,
  433. html: tTagBef1 + tHtml + tTagAft,
  434. image: tTagBef1 + tImage + tTagAft,
  435. text: tTagBef1 + tText + tTagAft,
  436. video: tTagBef2 + tVideo + tTagAft,
  437. audio: tTagBef2 + tAudio + tTagAft,
  438. flash: tTagBef2 + tFlash + tTagAft,
  439. object: tTagBef2 + tObject + tTagAft,
  440. pdf: tTagBef2 + tPdf + tTagAft,
  441. other: tTagBef2 + tOther + tTagAft
  442. };
  443. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'];
  444. defaultPreviewSettings = {
  445. image: {width: "auto", height: "160px"},
  446. html: {width: "213px", height: "160px"},
  447. text: {width: "213px", height: "160px"},
  448. video: {width: "213px", height: "160px"},
  449. audio: {width: "213px", height: "80px"},
  450. flash: {width: "213px", height: "160px"},
  451. object: {width: "160px", height: "160px"},
  452. pdf: {width: "160px", height: "160px"},
  453. other: {width: "160px", height: "160px"}
  454. };
  455. defaultPreviewZoomSettings = {
  456. image: {width: "100%", height: "100%"},
  457. html: {width: "100%", height: "100%", 'min-height': "480px"},
  458. text: {width: "100%", height: "100%", 'min-height': "480px"},
  459. video: {width: "auto", height: "100%", 'max-width': "100%"},
  460. audio: {width: "100%", height: "30px"},
  461. flash: {width: "auto", height: "480px"},
  462. object: {width: "auto", height: "100%", 'min-height': "480px"},
  463. pdf: {width: "100%", height: "100%", 'min-height': "480px"},
  464. other: {width: "auto", height: "100%", 'min-height': "480px"}
  465. };
  466. defaultFileTypeSettings = {
  467. image: function (vType, vName) {
  468. return compare(vType, 'image.*') || compare(vName, /\.(gif|png|jpe?g)$/i);
  469. },
  470. html: function (vType, vName) {
  471. return compare(vType, 'text/html') || compare(vName, /\.(htm|html)$/i);
  472. },
  473. text: function (vType, vName) {
  474. return compare(vType, 'text.*') || compare(vName, /\.(xml|javascript)$/i) ||
  475. compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  476. },
  477. video: function (vType, vName) {
  478. return compare(vType, 'video.*') && (compare(vType, /(ogg|mp4|mp?g|webm|3gp)$/i) ||
  479. compare(vName, /\.(og?|mp4|webm|mp?g|3gp)$/i));
  480. },
  481. audio: function (vType, vName) {
  482. return compare(vType, 'audio.*') && (compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  483. compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  484. },
  485. flash: function (vType, vName) {
  486. return compare(vType, 'application/x-shockwave-flash', true) || compare(vName, /\.(swf)$/i);
  487. },
  488. pdf: function (vType, vName) {
  489. return compare(vType, 'application/pdf', true) || compare(vName, /\.(pdf)$/i);
  490. },
  491. object: function () {
  492. return true;
  493. },
  494. other: function () {
  495. return true;
  496. }
  497. };
  498. isEmpty = function (value, trim) {
  499. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  500. };
  501. isArray = function (a) {
  502. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  503. };
  504. ifSet = function (needle, haystack, def) {
  505. def = def || '';
  506. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  507. };
  508. getElement = function (options, param, value) {
  509. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  510. };
  511. uniqId = function () {
  512. return Math.round(new Date().getTime() + (Math.random() * 100));
  513. };
  514. htmlEncode = function (str) {
  515. return str.replace(/&/g, '&amp;')
  516. .replace(/</g, '&lt;')
  517. .replace(/>/g, '&gt;')
  518. .replace(/"/g, '&quot;')
  519. .replace(/'/g, '&apos;');
  520. };
  521. replaceTags = function (str, tags) {
  522. var out = str;
  523. if (!tags) {
  524. return out;
  525. }
  526. $.each(tags, function (key, value) {
  527. if (typeof value === "function") {
  528. value = value();
  529. }
  530. out = out.split(key).join(value);
  531. });
  532. return out;
  533. };
  534. cleanMemory = function ($thumb) {
  535. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  536. /** @namespace objUrl.revokeObjectURL */
  537. objUrl.revokeObjectURL(data);
  538. };
  539. findFileName = function (filePath) {
  540. var sepIndex = filePath.lastIndexOf('/');
  541. if (sepIndex === -1) {
  542. sepIndex = filePath.lastIndexOf('\\');
  543. }
  544. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  545. };
  546. checkFullScreen = function () {
  547. //noinspection JSUnresolvedVariable
  548. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  549. document.msFullscreenElement;
  550. };
  551. toggleFullScreen = function (maximize) {
  552. if (maximize && !checkFullScreen()) {
  553. /** @namespace document.documentElement.requestFullscreen */
  554. /** @namespace document.documentElement.msRequestFullscreen */
  555. /** @namespace document.documentElement.mozRequestFullScreen */
  556. /** @namespace document.documentElement.webkitRequestFullscreen */
  557. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  558. if (document.documentElement.requestFullscreen) {
  559. document.documentElement.requestFullscreen();
  560. } else if (document.documentElement.msRequestFullscreen) {
  561. document.documentElement.msRequestFullscreen();
  562. } else if (document.documentElement.mozRequestFullScreen) {
  563. document.documentElement.mozRequestFullScreen();
  564. } else if (document.documentElement.webkitRequestFullscreen) {
  565. document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  566. }
  567. } else {
  568. /** @namespace document.exitFullscreen */
  569. /** @namespace document.msExitFullscreen */
  570. /** @namespace document.mozCancelFullScreen */
  571. /** @namespace document.webkitExitFullscreen */
  572. if (document.exitFullscreen) {
  573. document.exitFullscreen();
  574. } else if (document.msExitFullscreen) {
  575. document.msExitFullscreen();
  576. } else if (document.mozCancelFullScreen) {
  577. document.mozCancelFullScreen();
  578. } else if (document.webkitExitFullscreen) {
  579. document.webkitExitFullscreen();
  580. }
  581. }
  582. };
  583. moveArray = function (arr, oldIndex, newIndex) {
  584. if (newIndex >= arr.length) {
  585. var k = newIndex - arr.length;
  586. while ((k--) + 1) {
  587. arr.push(undefined);
  588. }
  589. }
  590. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  591. return arr;
  592. };
  593. FileInput = function (element, options) {
  594. var self = this;
  595. self.$element = $(element);
  596. if (!self._validate()) {
  597. return;
  598. }
  599. self.isPreviewable = hasFileAPISupport();
  600. self.isIE9 = isIE(9);
  601. self.isIE10 = isIE(10);
  602. if (self.isPreviewable || self.isIE9) {
  603. self._init(options);
  604. self._listen();
  605. } else {
  606. self.$element.removeClass('file-loading');
  607. }
  608. };
  609. FileInput.prototype = {
  610. constructor: FileInput,
  611. _init: function (options) {
  612. var self = this, $el = self.$element, t;
  613. $.each(options, function (key, value) {
  614. switch (key) {
  615. case 'minFileCount':
  616. case 'maxFileCount':
  617. case 'maxFileSize':
  618. self[key] = getNum(value);
  619. break;
  620. default:
  621. self[key] = value;
  622. break;
  623. }
  624. });
  625. self.fileInputCleared = false;
  626. self.fileBatchCompleted = true;
  627. if (!self.isPreviewable) {
  628. self.showPreview = false;
  629. }
  630. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  631. self.reader = null;
  632. self.formdata = {};
  633. self.clearStack();
  634. self.uploadCount = 0;
  635. self.uploadStatus = {};
  636. self.uploadLog = [];
  637. self.uploadAsyncCount = 0;
  638. self.loadedImages = [];
  639. self.totalImagesCount = 0;
  640. self.ajaxRequests = [];
  641. self.isError = false;
  642. self.ajaxAborted = false;
  643. self.cancelling = false;
  644. t = self._getLayoutTemplate('progress');
  645. self.progressTemplate = t.replace('{class}', self.progressClass);
  646. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  647. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  648. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  649. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  650. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  651. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  652. (self.isUploadable && self.dropZoneEnabled || !isEmpty(self.defaultPreviewContent));
  653. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  654. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  655. self.captionTemplate = self._getLayoutTemplate('caption');
  656. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  657. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  658. self.imageCanvas = document.createElement('canvas');
  659. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  660. }
  661. if (isEmpty(self.$element.attr('id'))) {
  662. self.$element.attr('id', uniqId());
  663. }
  664. if (self.$container === undefined) {
  665. self.$container = self._createContainer();
  666. } else {
  667. self._refreshContainer();
  668. }
  669. self.$dropZone = self.$container.find('.file-drop-zone');
  670. self.$progress = self.$container.find('.kv-upload-progress');
  671. self.$btnUpload = self.$container.find('.fileinput-upload');
  672. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  673. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  674. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  675. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  676. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  677. self.$errorContainer = getElement(options, 'elErrorContainer',
  678. self.$previewContainer.find('.kv-fileinput-error'));
  679. if (!isEmpty(self.msgErrorClass)) {
  680. addCss(self.$errorContainer, self.msgErrorClass);
  681. }
  682. self.$errorContainer.hide();
  683. self.fileActionSettings = $.extend(true, defaultFileActionSettings, options.fileActionSettings);
  684. self.previewInitId = "preview-" + uniqId();
  685. self.id = self.$element.attr('id');
  686. previewCache.init(self);
  687. self._initPreview(true);
  688. self._initPreviewActions();
  689. self.options = options;
  690. self._setFileDropZoneTitle();
  691. self.$element.removeClass('file-loading');
  692. if (self.$element.attr('disabled')) {
  693. self.disable();
  694. }
  695. self._initZoom();
  696. },
  697. _validate: function () {
  698. var self = this, $exception;
  699. if (self.$element.attr('type') === 'file') {
  700. return true;
  701. }
  702. $exception = '<div class="help-block alert alert-warning">' +
  703. '<h4>Invalid Input Type</h4>' +
  704. 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' +
  705. '</div>';
  706. self.$element.after($exception);
  707. return false;
  708. },
  709. _errorsExist: function () {
  710. var self = this, $err;
  711. if (self.$errorContainer.find('li').length) {
  712. return true;
  713. }
  714. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  715. $err.find('span.kv-error-close').remove();
  716. $err.find('ul').remove();
  717. return $.trim($err.text()).length ? true : false;
  718. },
  719. _errorHandler: function (evt, caption) {
  720. var self = this, err = evt.target.error;
  721. /** @namespace err.NOT_FOUND_ERR */
  722. /** @namespace err.SECURITY_ERR */
  723. /** @namespace err.NOT_READABLE_ERR */
  724. if (err.code === err.NOT_FOUND_ERR) {
  725. self._showError(self.msgFileNotFound.replace('{name}', caption));
  726. } else if (err.code === err.SECURITY_ERR) {
  727. self._showError(self.msgFileSecured.replace('{name}', caption));
  728. } else if (err.code === err.NOT_READABLE_ERR) {
  729. self._showError(self.msgFileNotReadable.replace('{name}', caption));
  730. } else if (err.code === err.ABORT_ERR) {
  731. self._showError(self.msgFilePreviewAborted.replace('{name}', caption));
  732. } else {
  733. self._showError(self.msgFilePreviewError.replace('{name}', caption));
  734. }
  735. },
  736. _addError: function (msg) {
  737. var self = this, $error = self.$errorContainer;
  738. if (msg && $error.length) {
  739. $error.html(self.errorCloseButton + msg);
  740. handler($error.find('.kv-error-close'), 'click', function () {
  741. $error.fadeOut('slow');
  742. });
  743. }
  744. },
  745. _resetErrors: function (fade) {
  746. var self = this, $error = self.$errorContainer;
  747. self.isError = false;
  748. self.$container.removeClass('has-error');
  749. $error.html('');
  750. if (fade) {
  751. $error.fadeOut('slow');
  752. } else {
  753. $error.hide();
  754. }
  755. },
  756. _showFolderError: function (folders) {
  757. var self = this, $error = self.$errorContainer, msg;
  758. if (!folders) {
  759. return;
  760. }
  761. msg = self.msgFoldersNotAllowed.replace(/\{n}/g, folders);
  762. self._addError(msg);
  763. addCss(self.$container, 'has-error');
  764. $error.fadeIn(800);
  765. self._raise('filefoldererror', [folders, msg]);
  766. },
  767. _showUploadError: function (msg, params, event) {
  768. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  769. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  770. if ($error.find('ul').length === 0) {
  771. self._addError('<ul>' + e + '</ul>');
  772. } else {
  773. $error.find('ul').append(e);
  774. }
  775. $error.fadeIn(800);
  776. self._raise(ev, [params, msg]);
  777. self.$container.removeClass('file-input-new');
  778. addCss(self.$container, 'has-error');
  779. return true;
  780. },
  781. _showError: function (msg, params, event) {
  782. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  783. params = params || {};
  784. params.reader = self.reader;
  785. self._addError(msg);
  786. $error.fadeIn(800);
  787. self._raise(ev, [params, msg]);
  788. if (!self.isUploadable) {
  789. self._clearFileInput();
  790. }
  791. self.$container.removeClass('file-input-new');
  792. addCss(self.$container, 'has-error');
  793. self.$btnUpload.attr('disabled', true);
  794. return true;
  795. },
  796. _noFilesError: function (params) {
  797. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  798. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  799. $error = self.$errorContainer;
  800. self._addError(msg);
  801. self.isError = true;
  802. self._updateFileDetails(0);
  803. $error.fadeIn(800);
  804. self._raise('fileerror', [params, msg]);
  805. self._clearFileInput();
  806. addCss(self.$container, 'has-error');
  807. },
  808. _parseError: function (jqXHR, errorThrown, fileName) {
  809. /** @namespace jqXHR.responseJSON */
  810. var self = this, errMsg = $.trim(errorThrown + ''),
  811. dot = errMsg.slice(-1) === '.' ? '' : '.',
  812. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  813. jqXHR.responseJSON.error : jqXHR.responseText;
  814. if (self.cancelling && self.msgUploadAborted) {
  815. errMsg = self.msgUploadAborted;
  816. }
  817. if (self.showAjaxErrorDetails && text) {
  818. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  819. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  820. errMsg += dot + text;
  821. } else {
  822. errMsg += dot;
  823. }
  824. self.cancelling = false;
  825. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  826. },
  827. _parseFileType: function (file) {
  828. var self = this, isValid, vType, cat, i;
  829. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  830. cat = defaultPreviewTypes[i];
  831. isValid = ifSet(cat, self.fileTypeSettings, defaultFileTypeSettings[cat]);
  832. vType = isValid(file.type, file.name) ? cat : '';
  833. if (!isEmpty(vType)) {
  834. return vType;
  835. }
  836. }
  837. return 'other';
  838. },
  839. _parseFilePreviewIcon: function (content, fname) {
  840. var self = this, proceed, ext, icn = self.previewFileIcon;
  841. if (fname && fname.indexOf('.') > -1) {
  842. ext = fname.split('.').pop();
  843. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  844. icn = self.previewFileIconSettings[ext];
  845. }
  846. if (self.previewFileExtSettings) {
  847. $.each(self.previewFileExtSettings, function (key, func) {
  848. if (self.previewFileIconSettings[key] && func(ext)) {
  849. icn = self.previewFileIconSettings[key];
  850. return;
  851. }
  852. proceed = true;
  853. });
  854. }
  855. }
  856. if (content.indexOf('{previewFileIcon}') > -1) {
  857. return content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace(
  858. /\{previewFileIcon}/g, icn);
  859. }
  860. return content;
  861. },
  862. _raise: function (event, params) {
  863. var self = this, e = $.Event(event);
  864. if (params !== undefined) {
  865. self.$element.trigger(e, params);
  866. } else {
  867. self.$element.trigger(e);
  868. }
  869. if (e.isDefaultPrevented()) {
  870. return false;
  871. }
  872. if (!e.result) {
  873. return e.result;
  874. }
  875. switch (event) {
  876. // ignore these events
  877. case 'filebatchuploadcomplete':
  878. case 'filebatchuploadsuccess':
  879. case 'fileuploaded':
  880. case 'fileclear':
  881. case 'filecleared':
  882. case 'filereset':
  883. case 'fileerror':
  884. case 'filefoldererror':
  885. case 'fileuploaderror':
  886. case 'filebatchuploaderror':
  887. case 'filedeleteerror':
  888. case 'filecustomerror':
  889. case 'filesuccessremove':
  890. break;
  891. // receive data response via `filecustomerror` event`
  892. default:
  893. self.ajaxAborted = e.result;
  894. break;
  895. }
  896. return true;
  897. },
  898. _listenFullScreen: function (isFullScreen) {
  899. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  900. if (!$modal || !$modal.length) {
  901. return;
  902. }
  903. $btnFull = $modal && $modal.find('.btn-fullscreen');
  904. $btnBord = $modal && $modal.find('.btn-borderless');
  905. if (!$btnFull.length || !$btnBord.length) {
  906. return;
  907. }
  908. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  909. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  910. if (isFullScreen) {
  911. $btnFull.addClass('active').attr('aria-pressed', 'true');
  912. } else {
  913. $btnBord.addClass('active').attr('aria-pressed', 'true');
  914. }
  915. if ($modal.hasClass('file-zoom-fullscreen')) {
  916. self._maximizeZoomDialog();
  917. } else {
  918. if (isFullScreen) {
  919. self._maximizeZoomDialog();
  920. } else {
  921. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  922. }
  923. }
  924. },
  925. _listen: function () {
  926. var self = this, $el = self.$element, $form = $el.closest('form'), $cont = self.$container;
  927. handler($el, 'change', $.proxy(self._change, self));
  928. if (self.showBrowse) {
  929. handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  930. }
  931. handler($form, 'reset', $.proxy(self.reset, self));
  932. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  933. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  934. self._initDragDrop();
  935. if (!self.isUploadable) {
  936. handler($form, 'submit', $.proxy(self._submitForm, self));
  937. }
  938. handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  939. handler($(window), 'resize', function () {
  940. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  941. });
  942. handler($(document), 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange',
  943. function () {
  944. self._listenFullScreen(checkFullScreen());
  945. });
  946. self._initClickable();
  947. },
  948. _initClickable: function () {
  949. var self = this, $zone;
  950. if (!self.isClickable) {
  951. return;
  952. }
  953. $zone = self.isUploadable ? self.$dropZone : self.$preview.find('.file-default-preview');
  954. addCss($zone, 'clickable');
  955. $zone.attr('tabindex', -1);
  956. handler($zone, 'click', function (e) {
  957. var $target = $(e.target);
  958. if (!$target.parents('.file-preview-thumbnails').length || $target.parents(
  959. '.file-default-preview').length) {
  960. self.$element.trigger('click');
  961. $zone.blur();
  962. }
  963. });
  964. },
  965. _initDragDrop: function () {
  966. var self = this, $zone = self.$dropZone;
  967. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  968. handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  969. handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  970. handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  971. handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  972. }
  973. },
  974. _zoneDragDropInit: function (e) {
  975. e.stopPropagation();
  976. e.preventDefault();
  977. },
  978. _zoneDragEnter: function (e) {
  979. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  980. self._zoneDragDropInit(e);
  981. if (self.isDisabled || !hasFiles) {
  982. e.originalEvent.dataTransfer.effectAllowed = 'none';
  983. e.originalEvent.dataTransfer.dropEffect = 'none';
  984. return;
  985. }
  986. addCss(self.$dropZone, 'file-highlighted');
  987. },
  988. _zoneDragLeave: function (e) {
  989. var self = this;
  990. self._zoneDragDropInit(e);
  991. if (self.isDisabled) {
  992. return;
  993. }
  994. self.$dropZone.removeClass('file-highlighted');
  995. },
  996. _zoneDrop: function (e) {
  997. var self = this;
  998. e.preventDefault();
  999. /** @namespace e.originalEvent.dataTransfer */
  1000. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  1001. return;
  1002. }
  1003. self._change(e, 'dragdrop');
  1004. self.$dropZone.removeClass('file-highlighted');
  1005. },
  1006. _uploadClick: function (e) {
  1007. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1008. isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  1009. if (e && e.isDefaultPrevented()) {
  1010. return;
  1011. }
  1012. if (!self.isUploadable) {
  1013. if (isEnabled && $btn.attr('type') !== 'submit') {
  1014. $form = $btn.closest('form');
  1015. // downgrade to normal form submit if possible
  1016. if ($form.length) {
  1017. $form.trigger('submit');
  1018. }
  1019. e.preventDefault();
  1020. }
  1021. return;
  1022. }
  1023. e.preventDefault();
  1024. if (isEnabled) {
  1025. self.upload();
  1026. }
  1027. },
  1028. _submitForm: function () {
  1029. var self = this, $el = self.$element, files = $el.get(0).files;
  1030. if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) {
  1031. self._noFilesError({});
  1032. return false;
  1033. }
  1034. return !self._abort({});
  1035. },
  1036. _clearPreview: function () {
  1037. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  1038. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  1039. $thumbs.remove();
  1040. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  1041. self._resetUpload();
  1042. }
  1043. self._validateDefaultPreview();
  1044. },
  1045. _initSortable: function () {
  1046. var self = this, $preview = self.$preview, $el, settings;
  1047. if (!window.KvSortable) {
  1048. return;
  1049. }
  1050. $el = $preview.find('.file-initial-thumbs');
  1051. //noinspection JSUnusedGlobalSymbols
  1052. settings = {
  1053. handle: '.drag-handle-init',
  1054. dataIdAttr: 'data-preview-id',
  1055. draggable: '.file-preview-initial',
  1056. onSort: function (e) {
  1057. var oldIndex = e.oldIndex, newIndex = e.newIndex;
  1058. self.initialPreview = moveArray(self.initialPreview, oldIndex, newIndex);
  1059. self.initialPreviewConfig = moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1060. previewCache.init(self);
  1061. self._raise('filesorted', {
  1062. previewId: $(e.item).attr('id'),
  1063. 'oldIndex': oldIndex,
  1064. 'newIndex': newIndex,
  1065. stack: self.initialPreviewConfig
  1066. });
  1067. }
  1068. };
  1069. if ($el.data('kvsortable')) {
  1070. $el.kvsortable('destroy');
  1071. }
  1072. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1073. $el.kvsortable(settings);
  1074. },
  1075. _initPreview: function (isInit) {
  1076. var self = this, cap = self.initialCaption || '', out;
  1077. if (!previewCache.count(self.id)) {
  1078. self._clearPreview();
  1079. if (isInit) {
  1080. self._setCaption(cap);
  1081. } else {
  1082. self._initCaption();
  1083. }
  1084. return;
  1085. }
  1086. out = previewCache.out(self.id);
  1087. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1088. self.$preview.html(out.content);
  1089. self._setCaption(cap);
  1090. self._initSortable();
  1091. if (!isEmpty(out.content)) {
  1092. self.$container.removeClass('file-input-new');
  1093. }
  1094. },
  1095. _getZoomButton: function (type) {
  1096. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1097. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1098. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1099. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1100. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1101. }
  1102. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1103. },
  1104. _getModalContent: function () {
  1105. var self = this;
  1106. return self._getLayoutTemplate('modal')
  1107. .replace(/\{heading}/g, self.msgZoomModalHeading)
  1108. .replace(/\{prev}/g, self._getZoomButton('prev'))
  1109. .replace(/\{next}/g, self._getZoomButton('next'))
  1110. .replace(/\{toggleheader}/g, self._getZoomButton('toggleheader'))
  1111. .replace(/\{fullscreen}/g, self._getZoomButton('fullscreen'))
  1112. .replace(/\{borderless}/g, self._getZoomButton('borderless'))
  1113. .replace(/\{close}/g, self._getZoomButton('close'));
  1114. },
  1115. _listenModalEvent: function (event) {
  1116. var self = this, $modal = self.$modal, getParams = function (e) {
  1117. return {
  1118. sourceEvent: e,
  1119. previewId: $modal.data('previewId'),
  1120. modal: $modal
  1121. };
  1122. };
  1123. $modal.on(event + '.bs.modal', function (e) {
  1124. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1125. self._raise('filezoom' + event, getParams(e));
  1126. if (event === 'shown') {
  1127. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1128. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1129. if ($modal.hasClass('file-zoom-fullscreen')) {
  1130. self._maximizeZoomDialog();
  1131. if (checkFullScreen()) {
  1132. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1133. } else {
  1134. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1135. }
  1136. }
  1137. }
  1138. });
  1139. },
  1140. _initZoom: function () {
  1141. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + MODAL_ID;
  1142. self.$modal = $(modalId);
  1143. if (!self.$modal || !self.$modal.length) {
  1144. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1145. self.$modal = $('#' + MODAL_ID).insertBefore($dialog);
  1146. $dialog.remove();
  1147. }
  1148. self.$modal.html(self._getModalContent());
  1149. self._listenModalEvent('show');
  1150. self._listenModalEvent('shown');
  1151. self._listenModalEvent('hide');
  1152. self._listenModalEvent('hidden');
  1153. self._listenModalEvent('loaded');
  1154. },
  1155. _initZoomButtons: function () {
  1156. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  1157. frames = self.$preview.find('.file-preview-frame').toArray(), len = frames.length,
  1158. $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next');
  1159. if (!len) {
  1160. return;
  1161. }
  1162. $first = $(frames[0]);
  1163. $last = $(frames[len - 1]);
  1164. $prev.removeAttr('disabled');
  1165. $next.removeAttr('disabled');
  1166. if ($first.length && $first.attr('id') === previewId) {
  1167. $prev.attr('disabled', true);
  1168. }
  1169. if ($last.length && $last.attr('id') === previewId) {
  1170. $next.attr('disabled', true);
  1171. }
  1172. },
  1173. _maximizeZoomDialog: function () {
  1174. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1175. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1176. h = $(window).height(), diff = 0;
  1177. $modal.addClass('file-zoom-fullscreen');
  1178. if ($head && $head.length) {
  1179. h -= $head.outerHeight(true);
  1180. }
  1181. if ($foot && $foot.length) {
  1182. h -= $foot.outerHeight(true);
  1183. }
  1184. if ($body && $body.length) {
  1185. diff = $body.outerHeight(true) - $body.height();
  1186. h -= diff;
  1187. }
  1188. $modal.find('.kv-zoom-body').height(h);
  1189. },
  1190. _resizeZoomDialog: function (fullScreen) {
  1191. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1192. $btnBord = $modal.find('.btn-borderless');
  1193. if ($modal.hasClass('file-zoom-fullscreen')) {
  1194. toggleFullScreen(false);
  1195. if (!fullScreen) {
  1196. if (!$btnFull.hasClass('active')) {
  1197. $modal.removeClass('file-zoom-fullscreen');
  1198. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1199. } else {
  1200. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1201. }
  1202. } else {
  1203. if (!$btnFull.hasClass('active')) {
  1204. $modal.removeClass('file-zoom-fullscreen');
  1205. self._resizeZoomDialog(true);
  1206. if ($btnBord.hasClass('active')) {
  1207. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1208. }
  1209. }
  1210. }
  1211. } else {
  1212. if (!fullScreen) {
  1213. self._maximizeZoomDialog();
  1214. return;
  1215. }
  1216. toggleFullScreen(true);
  1217. }
  1218. $modal.focus();
  1219. },
  1220. _setZoomContent: function ($preview, animate) {
  1221. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $preview.attr('id'),
  1222. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1223. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'),
  1224. $btnTogh = $modal.find('.btn-toggleheader');
  1225. tmplt = $preview.data('template') || 'generic';
  1226. $content = $preview.find('.kv-file-content');
  1227. body = $content.length ? $content.html() : '';
  1228. title = $preview.find('.file-footer-caption').text() || '';
  1229. $modal.find('.kv-zoom-title').html(title);
  1230. $body = $modal.find('.kv-zoom-body');
  1231. if (animate) {
  1232. $tmp = $body.clone().insertAfter($body);
  1233. $body.html(body).hide();
  1234. $tmp.fadeOut('fast', function () {
  1235. $body.fadeIn('fast');
  1236. $tmp.remove();
  1237. });
  1238. } else {
  1239. $body.html(body);
  1240. }
  1241. config = self.previewZoomSettings[tmplt];
  1242. if (config) {
  1243. $dataEl = $body.find('.kv-preview-data');
  1244. addCss($dataEl, 'file-zoom-detail');
  1245. $.each(config, function (key, value) {
  1246. $dataEl.css(key, value);
  1247. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1248. $dataEl.removeAttr(key);
  1249. }
  1250. });
  1251. }
  1252. $modal.data('previewId', previewId);
  1253. handler($prev, 'click', function () {
  1254. self._zoomSlideShow('prev', previewId);
  1255. });
  1256. handler($next, 'click', function () {
  1257. self._zoomSlideShow('next', previewId);
  1258. });
  1259. handler($btnFull, 'click', function () {
  1260. self._resizeZoomDialog(true);
  1261. });
  1262. handler($btnBord, 'click', function () {
  1263. self._resizeZoomDialog(false);
  1264. });
  1265. handler($btnTogh, 'click', function () {
  1266. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1267. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1268. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1269. if ($modal.hasClass('file-zoom-fullscreen')) {
  1270. h = $body.outerHeight(true);
  1271. if (!height) {
  1272. h = h - $header.outerHeight(true);
  1273. }
  1274. }
  1275. $body.css('height', height ? h + height : h);
  1276. };
  1277. if ($header.is(':visible')) {
  1278. ht = $header.outerHeight(true);
  1279. $header.slideUp('slow', function () {
  1280. $actions.find('.btn').appendTo($floatBar);
  1281. resize(ht);
  1282. });
  1283. } else {
  1284. $floatBar.find('.btn').appendTo($actions);
  1285. $header.slideDown('slow', function () {
  1286. resize();
  1287. });
  1288. }
  1289. $modal.focus();
  1290. });
  1291. handler($modal, 'keydown', function (e) {
  1292. var key = e.which || e.keyCode;
  1293. if (key === 37 && !$prev.attr('disabled')) {
  1294. self._zoomSlideShow('prev', previewId);
  1295. }
  1296. if (key === 39 && !$next.attr('disabled')) {
  1297. self._zoomSlideShow('next', previewId);
  1298. }
  1299. });
  1300. },
  1301. _zoomPreview: function ($btn) {
  1302. var self = this, $preview;
  1303. if (!$btn.length) {
  1304. throw 'Cannot zoom to detailed preview!';
  1305. }
  1306. self.$modal.html(self._getModalContent());
  1307. $preview = $btn.closest('.file-preview-frame');
  1308. self._setZoomContent($preview);
  1309. self.$modal.modal('show');
  1310. self._initZoomButtons();
  1311. },
  1312. _zoomSlideShow: function (dir, previewId) {
  1313. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1314. frames = self.$preview.find('.file-preview-frame').toArray(), len = frames.length, out;
  1315. if ($btn.attr('disabled')) {
  1316. return;
  1317. }
  1318. for (i = 0; i < len; i++) {
  1319. if ($(frames[i]).attr('id') === previewId) {
  1320. out = dir === 'prev' ? i - 1 : i + 1;
  1321. break;
  1322. }
  1323. }
  1324. if (out < 0 || out >= len || !frames[out]) {
  1325. return;
  1326. }
  1327. $targFrame = $(frames[out]);
  1328. if ($targFrame.length) {
  1329. self._setZoomContent($targFrame, true);
  1330. }
  1331. self._initZoomButtons();
  1332. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1333. },
  1334. _initZoomButton: function () {
  1335. var self = this;
  1336. self.$preview.find('.kv-file-zoom').each(function () {
  1337. var $el = $(this);
  1338. handler($el, 'click', function () {
  1339. self._zoomPreview($el);
  1340. });
  1341. });
  1342. },
  1343. _initPreviewActions: function () {
  1344. var self = this, deleteExtraData = self.deleteExtraData || {},
  1345. resetProgress = function () {
  1346. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  1347. if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) {
  1348. self.reset();
  1349. self.initialCaption = '';
  1350. }
  1351. };
  1352. self._initZoomButton();
  1353. self.$preview.find('.kv-file-remove').each(function () {
  1354. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1355. if (isEmpty(vUrl) || vKey === undefined) {
  1356. return;
  1357. }
  1358. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  1359. settings, params, index = $frame.data('fileindex'), config, extraData;
  1360. index = parseInt(index.replace('init_', ''));
  1361. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1362. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1363. if (typeof extraData === "function") {
  1364. extraData = extraData();
  1365. }
  1366. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1367. settings = $.extend(true, {}, {
  1368. url: vUrl,
  1369. type: 'POST',
  1370. dataType: 'json',
  1371. data: $.extend(true, {}, {key: vKey}, extraData),
  1372. beforeSend: function (jqXHR) {
  1373. self.ajaxAborted = false;
  1374. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  1375. if (self.ajaxAborted) {
  1376. jqXHR.abort();
  1377. } else {
  1378. addCss($frame, 'file-uploading');
  1379. addCss($el, 'disabled');
  1380. }
  1381. },
  1382. success: function (data, textStatus, jqXHR) {
  1383. var n, cap;
  1384. if (isEmpty(data) || isEmpty(data.error)) {
  1385. previewCache.unset(self.id, index);
  1386. n = previewCache.count(self.id);
  1387. cap = n > 0 ? self._getMsgSelected(n) : '';
  1388. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  1389. self._setCaption(cap);
  1390. } else {
  1391. params.jqXHR = jqXHR;
  1392. params.response = data;
  1393. self._showError(data.error, params, 'filedeleteerror');
  1394. $frame.removeClass('file-uploading');
  1395. $el.removeClass('disabled');
  1396. resetProgress();
  1397. return;
  1398. }
  1399. $frame.removeClass('file-uploading').addClass('file-deleted');
  1400. $frame.fadeOut('slow', function () {
  1401. self._clearObjects($frame);
  1402. $frame.remove();
  1403. resetProgress();
  1404. if (!n && self.getFileStack().length === 0) {
  1405. self._setCaption('');
  1406. self.reset();
  1407. }
  1408. });
  1409. },
  1410. error: function (jqXHR, textStatus, errorThrown) {
  1411. var errMsg = self._parseError(jqXHR, errorThrown);
  1412. params.jqXHR = jqXHR;
  1413. params.response = {};
  1414. self._showError(errMsg, params, 'filedeleteerror');
  1415. $frame.removeClass('file-uploading');
  1416. resetProgress();
  1417. }
  1418. }, self.ajaxDeleteSettings);
  1419. handler($el, 'click', function () {
  1420. if (!self._validateMinCount()) {
  1421. return false;
  1422. }
  1423. $.ajax(settings);
  1424. });
  1425. });
  1426. },
  1427. _clearObjects: function ($el) {
  1428. $el.find('video audio').each(function () {
  1429. this.pause();
  1430. $(this).remove();
  1431. });
  1432. $el.find('img object div').each(function () {
  1433. $(this).remove();
  1434. });
  1435. },
  1436. _clearFileInput: function () {
  1437. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1438. if (isEmpty($el.val())) {
  1439. return;
  1440. }
  1441. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1442. // crashing but still allow clearing of the file input.
  1443. if (self.isIE9 || self.isIE10) {
  1444. $srcFrm = $el.closest('form');
  1445. $tmpFrm = $(document.createElement('form'));
  1446. $tmpEl = $(document.createElement('div'));
  1447. $el.before($tmpEl);
  1448. if ($srcFrm.length) {
  1449. $srcFrm.after($tmpFrm);
  1450. } else {
  1451. $tmpEl.after($tmpFrm);
  1452. }
  1453. $tmpFrm.append($el).trigger('reset');
  1454. $tmpEl.before($el).remove();
  1455. $tmpFrm.remove();
  1456. } else { // normal input clear behavior for other sane browsers
  1457. $el.val('');
  1458. }
  1459. self.fileInputCleared = true;
  1460. },
  1461. _resetUpload: function () {
  1462. var self = this;
  1463. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1464. self.uploadCount = 0;
  1465. self.uploadStatus = {};
  1466. self.uploadLog = [];
  1467. self.uploadAsyncCount = 0;
  1468. self.loadedImages = [];
  1469. self.totalImagesCount = 0;
  1470. self.$btnUpload.removeAttr('disabled');
  1471. self._setProgress(0);
  1472. addCss(self.$progress, 'hide');
  1473. self._resetErrors(false);
  1474. self.ajaxAborted = false;
  1475. self.ajaxRequests = [];
  1476. self._resetCanvas();
  1477. },
  1478. _resetCanvas: function () {
  1479. var self = this;
  1480. if (self.canvas && self.imageCanvasContext) {
  1481. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1482. }
  1483. },
  1484. _hasInitialPreview: function () {
  1485. var self = this;
  1486. return !self.overwriteInitial && previewCache.count(self.id);
  1487. },
  1488. _resetPreview: function () {
  1489. var self = this, out, cap;
  1490. if (previewCache.count(self.id)) {
  1491. out = previewCache.out(self.id);
  1492. self.$preview.html(out.content);
  1493. cap = self.initialCaption ? self.initialCaption : out.caption;
  1494. self._setCaption(cap);
  1495. } else {
  1496. self._clearPreview();
  1497. self._initCaption();
  1498. }
  1499. if (self.showPreview) {
  1500. self._initZoom();
  1501. self._initSortable();
  1502. }
  1503. },
  1504. _clearDefaultPreview: function () {
  1505. var self = this;
  1506. self.$preview.find('.file-default-preview').remove();
  1507. },
  1508. _validateDefaultPreview: function () {
  1509. var self = this;
  1510. if (!self.showPreview || isEmpty(self.defaultPreviewContent)) {
  1511. return;
  1512. }
  1513. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1514. self.$container.removeClass('file-input-new');
  1515. self._initClickable();
  1516. },
  1517. _resetPreviewThumbs: function (isAjax) {
  1518. var self = this, out;
  1519. if (isAjax) {
  1520. self._clearPreview();
  1521. self.clearStack();
  1522. return;
  1523. }
  1524. if (self._hasInitialPreview()) {
  1525. out = previewCache.out(self.id);
  1526. self.$preview.html(out.content);
  1527. self._setCaption(out.caption);
  1528. self._initPreviewActions();
  1529. } else {
  1530. self._clearPreview();
  1531. }
  1532. },
  1533. _getLayoutTemplate: function (t) {
  1534. var self = this,
  1535. template = ifSet(t, self.layoutTemplates, defaultLayoutTemplates[t]);
  1536. if (isEmpty(self.customLayoutTags)) {
  1537. return template;
  1538. }
  1539. return replaceTags(template, self.customLayoutTags);
  1540. },
  1541. _getPreviewTemplate: function (t) {
  1542. var self = this,
  1543. template = ifSet(t, self.previewTemplates, defaultPreviewTemplates[t]);
  1544. if (isEmpty(self.customPreviewTags)) {
  1545. return template;
  1546. }
  1547. return replaceTags(template, self.customPreviewTags);
  1548. },
  1549. _getOutData: function (jqXHR, responseData, filesData) {
  1550. var self = this;
  1551. jqXHR = jqXHR || {};
  1552. responseData = responseData || {};
  1553. filesData = filesData || self.filestack.slice(0) || {};
  1554. return {
  1555. form: self.formdata,
  1556. files: filesData,
  1557. filenames: self.filenames,
  1558. filescount: self.getFilesCount(),
  1559. extra: self._getExtraData(),
  1560. response: responseData,
  1561. reader: self.reader,
  1562. jqXHR: jqXHR
  1563. };
  1564. },
  1565. _getMsgSelected: function (n) {
  1566. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1567. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1568. },
  1569. _getThumbs: function (css) {
  1570. css = css || '';
  1571. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1572. },
  1573. _getExtraData: function (previewId, index) {
  1574. var self = this, data = self.uploadExtraData;
  1575. if (typeof self.uploadExtraData === "function") {
  1576. data = self.uploadExtraData(previewId, index);
  1577. }
  1578. return data;
  1579. },
  1580. _initXhr: function (xhrobj, previewId, fileCount) {
  1581. var self = this;
  1582. if (xhrobj.upload) {
  1583. xhrobj.upload.addEventListener('progress', function (event) {
  1584. var pct = 0, total = event.total, position = event.loaded || event.position;
  1585. /** @namespace event.lengthComputable */
  1586. if (event.lengthComputable) {
  1587. pct = Math.floor(position / total * 100);
  1588. }
  1589. if (previewId) {
  1590. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1591. } else {
  1592. self._setProgress(pct);
  1593. }
  1594. }, false);
  1595. }
  1596. return xhrobj;
  1597. },
  1598. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1599. var self = this, settings;
  1600. self._raise('filepreajax', [previewId, index]);
  1601. self._uploadExtra(previewId, index);
  1602. settings = $.extend(true, {}, {
  1603. xhr: function () {
  1604. var xhrobj = $.ajaxSettings.xhr();
  1605. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1606. },
  1607. url: self.uploadUrl,
  1608. type: 'POST',
  1609. dataType: 'json',
  1610. data: self.formdata,
  1611. cache: false,
  1612. processData: false,
  1613. contentType: false,
  1614. beforeSend: fnBefore,
  1615. success: fnSuccess,
  1616. complete: fnComplete,
  1617. error: fnError
  1618. }, self.ajaxSettings);
  1619. self.ajaxRequests.push($.ajax(settings));
  1620. },
  1621. _initUploadSuccess: function (out, $thumb, allFiles) {
  1622. var self = this, append, data, index, $newThumb, content, config, tags, i,
  1623. mergeArray = function (prop, content) {
  1624. if (!(self[prop] instanceof Array)) {
  1625. self[prop] = [];
  1626. }
  1627. if (content && content.length) {
  1628. self[prop] = self[prop].concat(content);
  1629. }
  1630. };
  1631. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1632. return;
  1633. }
  1634. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1635. self.hasInitData = true;
  1636. content = out.initialPreview || [];
  1637. config = out.initialPreviewConfig || [];
  1638. tags = out.initialPreviewThumbTags || [];
  1639. append = out.append === undefined || out.append ? true : false;
  1640. if (content.length > 0 && !isArray(content)) {
  1641. content = content.split(self.initialPreviewDelimiter);
  1642. }
  1643. self.overwriteInitial = false;
  1644. mergeArray('initialPreview', content);
  1645. mergeArray('initialPreviewConfig', config);
  1646. mergeArray('initialPreviewThumbTags', tags);
  1647. if ($thumb !== undefined) {
  1648. if (!allFiles) {
  1649. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1650. data = previewCache.get(self.id, index, false);
  1651. $newThumb = $(data).hide();
  1652. $thumb.after($newThumb).fadeOut('slow', function () {
  1653. $newThumb.fadeIn('slow').css('display:inline-block');
  1654. self._initPreviewActions();
  1655. self._clearFileInput();
  1656. $thumb.remove();
  1657. });
  1658. } else {
  1659. i = $thumb.attr('data-fileindex');
  1660. self.uploadCache.content[i] = content[0];
  1661. self.uploadCache.config[i] = config[0] || [];
  1662. self.uploadCache.tags[i] = tags[0] || [];
  1663. self.uploadCache.append = append;
  1664. }
  1665. } else {
  1666. previewCache.set(self.id, content, config, tags, append);
  1667. self._initPreview();
  1668. self._initPreviewActions();
  1669. }
  1670. }
  1671. },
  1672. _initSuccessThumbs: function () {
  1673. var self = this;
  1674. if (!self.showPreview) {
  1675. return;
  1676. }
  1677. self._getThumbs('.file-preview-success').each(function () {
  1678. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1679. $remove.removeAttr('disabled');
  1680. handler($remove, 'click', function () {
  1681. var out = self._raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1682. cleanMemory($thumb);
  1683. if (out === false) {
  1684. return;
  1685. }
  1686. $thumb.fadeOut('slow', function () {
  1687. $thumb.remove();
  1688. if (!self.$preview.find('.file-preview-frame').length) {
  1689. self.reset();
  1690. }
  1691. });
  1692. });
  1693. });
  1694. },
  1695. _checkAsyncComplete: function () {
  1696. var self = this, previewId, i;
  1697. for (i = 0; i < self.filestack.length; i++) {
  1698. if (self.filestack[i]) {
  1699. previewId = self.previewInitId + "-" + i;
  1700. if ($.inArray(previewId, self.uploadLog) === -1) {
  1701. return false;
  1702. }
  1703. }
  1704. }
  1705. return (self.uploadAsyncCount === self.uploadLog.length);
  1706. },
  1707. _uploadExtra: function (previewId, index) {
  1708. var self = this, data = self._getExtraData(previewId, index);
  1709. if (data.length === 0) {
  1710. return;
  1711. }
  1712. $.each(data, function (key, value) {
  1713. self.formdata.append(key, value);
  1714. });
  1715. },
  1716. _uploadSingle: function (i, files, allFiles) {
  1717. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1718. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1719. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1720. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1721. self.formdata = formdata;
  1722. if (self.showPreview) {
  1723. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1724. $btnUpload = $thumb.find('.kv-file-upload');
  1725. $btnDelete = $thumb.find('.kv-file-remove');
  1726. $('#' + previewId).find('.file-thumb-progress').removeClass('hide');
  1727. }
  1728. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1729. return;
  1730. }
  1731. updateUploadLog = function (i, previewId) {
  1732. self.updateStack(i, undefined);
  1733. self.uploadLog.push(previewId);
  1734. if (self._checkAsyncComplete()) {
  1735. self.fileBatchCompleted = true;
  1736. }
  1737. };
  1738. chkComplete = function () {
  1739. var u = self.uploadCache;
  1740. if (!self.fileBatchCompleted) {
  1741. return;
  1742. }
  1743. setTimeout(function () {
  1744. if (self.showPreview) {
  1745. previewCache.set(self.id, u.content, u.config, u.tags, u.append);
  1746. if (self.hasInitData) {
  1747. self._initPreview();
  1748. self._initPreviewActions();
  1749. }
  1750. }
  1751. self.unlock();
  1752. self._clearFileInput();
  1753. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1754. self.uploadCount = 0;
  1755. self.uploadStatus = {};
  1756. self.uploadLog = [];
  1757. self._setProgress(101);
  1758. }, 100);
  1759. };
  1760. fnBefore = function (jqXHR) {
  1761. outData = self._getOutData(jqXHR);
  1762. self.fileBatchCompleted = false;
  1763. if (self.showPreview) {
  1764. if (!$thumb.hasClass('file-preview-success')) {
  1765. self._setThumbStatus($thumb, 'Loading');
  1766. addCss($thumb, 'file-uploading');
  1767. }
  1768. $btnUpload.attr('disabled', true);
  1769. $btnDelete.attr('disabled', true);
  1770. }
  1771. if (!allFiles) {
  1772. self.lock();
  1773. }
  1774. self._raise('filepreupload', [outData, previewId, i]);
  1775. $.extend(true, params, outData);
  1776. if (self._abort(params)) {
  1777. jqXHR.abort();
  1778. self._setProgressCancelled();
  1779. }
  1780. };
  1781. fnSuccess = function (data, textStatus, jqXHR) {
  1782. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  1783. outData = self._getOutData(jqXHR, data);
  1784. $.extend(true, params, outData);
  1785. setTimeout(function () {
  1786. if (isEmpty(data) || isEmpty(data.error)) {
  1787. if (self.showPreview) {
  1788. self._setThumbStatus($thumb, 'Success');
  1789. $btnUpload.hide();
  1790. self._initUploadSuccess(data, $thumb, allFiles);
  1791. }
  1792. self._raise('fileuploaded', [outData, pid, i]);
  1793. if (!allFiles) {
  1794. self.updateStack(i, undefined);
  1795. } else {
  1796. updateUploadLog(i, pid);
  1797. }
  1798. } else {
  1799. self._showUploadError(data.error, params);
  1800. self._setPreviewError($thumb, i);
  1801. if (allFiles) {
  1802. updateUploadLog(i, pid);
  1803. }
  1804. }
  1805. }, 100);
  1806. };
  1807. fnComplete = function () {
  1808. setTimeout(function () {
  1809. if (self.showPreview) {
  1810. $btnUpload.removeAttr('disabled');
  1811. $btnDelete.removeAttr('disabled');
  1812. $thumb.removeClass('file-uploading');
  1813. self._setProgress(101, $('#' + previewId).find('.file-thumb-progress'));
  1814. }
  1815. if (!allFiles) {
  1816. self.unlock(false);
  1817. self._clearFileInput();
  1818. } else {
  1819. chkComplete();
  1820. }
  1821. self._initSuccessThumbs();
  1822. }, 100);
  1823. };
  1824. fnError = function (jqXHR, textStatus, errorThrown) {
  1825. var errMsg = self._parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1826. setTimeout(function () {
  1827. if (allFiles) {
  1828. updateUploadLog(i, previewId);
  1829. }
  1830. self.uploadStatus[previewId] = 100;
  1831. self._setPreviewError($thumb, i);
  1832. $.extend(true, params, self._getOutData(jqXHR));
  1833. self._showUploadError(errMsg, params);
  1834. }, 100);
  1835. };
  1836. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1837. formdata.append('file_id', i);
  1838. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1839. },
  1840. _uploadBatch: function () {
  1841. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1842. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1843. setAllUploaded;
  1844. self.formdata = new FormData();
  1845. if (total === 0 || !hasPostData || self._abort(params)) {
  1846. return;
  1847. }
  1848. setAllUploaded = function () {
  1849. $.each(files, function (key) {
  1850. self.updateStack(key, undefined);
  1851. });
  1852. self._clearFileInput();
  1853. };
  1854. fnBefore = function (jqXHR) {
  1855. self.lock();
  1856. var outData = self._getOutData(jqXHR);
  1857. if (self.showPreview) {
  1858. self._getThumbs().each(function () {
  1859. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1860. $btnDelete = $thumb.find('.kv-file-remove');
  1861. if (!$thumb.hasClass('file-preview-success')) {
  1862. self._setThumbStatus($thumb, 'Loading');
  1863. addCss($thumb, 'file-uploading');
  1864. }
  1865. $btnUpload.attr('disabled', true);
  1866. $btnDelete.attr('disabled', true);
  1867. });
  1868. }
  1869. self._raise('filebatchpreupload', [outData]);
  1870. if (self._abort(outData)) {
  1871. jqXHR.abort();
  1872. self._setProgressCancelled();
  1873. }
  1874. };
  1875. fnSuccess = function (data, textStatus, jqXHR) {
  1876. /** @namespace data.errorkeys */
  1877. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(':not(.file-preview-error)'), key = 0,
  1878. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1879. if (isEmpty(data) || isEmpty(data.error)) {
  1880. self._raise('filebatchuploadsuccess', [outData]);
  1881. setAllUploaded();
  1882. if (self.showPreview) {
  1883. $thumbs.each(function () {
  1884. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1885. $thumb.find('.kv-file-upload').hide();
  1886. self._setThumbStatus($thumb, 'Success');
  1887. $thumb.removeClass('file-uploading');
  1888. $btnUpload.removeAttr('disabled');
  1889. });
  1890. self._initUploadSuccess(data);
  1891. } else {
  1892. self.reset();
  1893. }
  1894. } else {
  1895. if (self.showPreview) {
  1896. $thumbs.each(function () {
  1897. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1898. $btnUpload = $thumb.find('.kv-file-upload');
  1899. $thumb.removeClass('file-uploading');
  1900. $btnUpload.removeAttr('disabled');
  1901. $btnDelete.removeAttr('disabled');
  1902. if (keys.length === 0) {
  1903. self._setPreviewError($thumb);
  1904. return;
  1905. }
  1906. if ($.inArray(key, keys) !== -1) {
  1907. self._setPreviewError($thumb);
  1908. } else {
  1909. $thumb.find('.kv-file-upload').hide();
  1910. self._setThumbStatus($thumb, 'Success');
  1911. self.updateStack(key, undefined);
  1912. }
  1913. key++;
  1914. });
  1915. self._initUploadSuccess(data);
  1916. }
  1917. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1918. }
  1919. };
  1920. fnComplete = function () {
  1921. self._setProgress(101);
  1922. self.unlock();
  1923. self._initSuccessThumbs();
  1924. self._clearFileInput();
  1925. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1926. };
  1927. fnError = function (jqXHR, textStatus, errorThrown) {
  1928. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  1929. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1930. self.uploadFileCount = total - 1;
  1931. if (!self.showPreview) {
  1932. return;
  1933. }
  1934. self._getThumbs().each(function () {
  1935. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1936. $thumb.removeClass('file-uploading');
  1937. if (self.filestack[key] !== undefined) {
  1938. self._setPreviewError($thumb);
  1939. }
  1940. });
  1941. self._getThumbs().removeClass('file-uploading');
  1942. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  1943. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  1944. };
  1945. $.each(files, function (key, data) {
  1946. if (!isEmpty(files[key])) {
  1947. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  1948. }
  1949. });
  1950. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1951. },
  1952. _uploadExtraOnly: function () {
  1953. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1954. self.formdata = new FormData();
  1955. if (self._abort(params)) {
  1956. return;
  1957. }
  1958. fnBefore = function (jqXHR) {
  1959. self.lock();
  1960. var outData = self._getOutData(jqXHR);
  1961. self._raise('filebatchpreupload', [outData]);
  1962. self._setProgress(50);
  1963. params.data = outData;
  1964. params.xhr = jqXHR;
  1965. if (self._abort(params)) {
  1966. jqXHR.abort();
  1967. self._setProgressCancelled();
  1968. }
  1969. };
  1970. fnSuccess = function (data, textStatus, jqXHR) {
  1971. var outData = self._getOutData(jqXHR, data);
  1972. if (isEmpty(data) || isEmpty(data.error)) {
  1973. self._raise('filebatchuploadsuccess', [outData]);
  1974. self._clearFileInput();
  1975. self._initUploadSuccess(data);
  1976. } else {
  1977. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1978. }
  1979. };
  1980. fnComplete = function () {
  1981. self._setProgress(101);
  1982. self.unlock();
  1983. self._clearFileInput();
  1984. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1985. };
  1986. fnError = function (jqXHR, textStatus, errorThrown) {
  1987. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  1988. params.data = outData;
  1989. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1990. };
  1991. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1992. },
  1993. _initFileActions: function () {
  1994. var self = this;
  1995. if (!self.showPreview) {
  1996. return;
  1997. }
  1998. self._initZoomButton();
  1999. self.$preview.find('.kv-file-remove').each(function () {
  2000. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  2001. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  2002. handler($el, 'click', function () {
  2003. status = self._raise('filepreremove', [id, ind]);
  2004. if (status === false || !self._validateMinCount()) {
  2005. return false;
  2006. }
  2007. hasError = $frame.hasClass('file-preview-error');
  2008. cleanMemory($frame);
  2009. $frame.fadeOut('slow', function () {
  2010. self.updateStack(ind, undefined);
  2011. self._clearObjects($frame);
  2012. $frame.remove();
  2013. if (id && hasError) {
  2014. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2015. $(this).remove();
  2016. if (!self._errorsExist()) {
  2017. self._resetErrors();
  2018. }
  2019. });
  2020. }
  2021. self._clearFileInput();
  2022. var filestack = self.getFileStack(true), chk = previewCache.count(self.id),
  2023. len = filestack.length,
  2024. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  2025. if (len === 0 && chk === 0 && !hasThumb) {
  2026. self.reset();
  2027. } else {
  2028. n = chk + len;
  2029. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2030. self._setCaption(cap);
  2031. }
  2032. self._raise('fileremoved', [id, ind]);
  2033. });
  2034. });
  2035. });
  2036. self.$preview.find('.kv-file-upload').each(function () {
  2037. var $el = $(this);
  2038. handler($el, 'click', function () {
  2039. var $frame = $el.closest('.file-preview-frame'),
  2040. ind = $frame.attr('data-fileindex');
  2041. if (!$frame.hasClass('file-preview-error')) {
  2042. self._uploadSingle(ind, self.filestack, false);
  2043. }
  2044. });
  2045. });
  2046. },
  2047. _hideFileIcon: function () {
  2048. if (this.overwriteInitial) {
  2049. this.$captionContainer.find('.kv-caption-icon').hide();
  2050. }
  2051. },
  2052. _showFileIcon: function () {
  2053. this.$captionContainer.find('.kv-caption-icon').show();
  2054. },
  2055. _getSize: function (bytes) {
  2056. var size = parseFloat(bytes);
  2057. if (bytes === null || isNaN(size)) {
  2058. return '';
  2059. }
  2060. var self = this, i, func = self.fileSizeGetter, sizes, out;
  2061. if (typeof func === 'function') {
  2062. out = func(bytes);
  2063. } else {
  2064. i = Math.floor(Math.log(size) / Math.log(1024));
  2065. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2066. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2067. }
  2068. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2069. },
  2070. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind) {
  2071. var self = this, tmplt = self._getPreviewTemplate(cat), content, sText, css = frameClass || '',
  2072. config = ifSet(cat, self.previewSettings, defaultPreviewSettings[cat]), caption = self.slug(fname),
  2073. footer = foot || self._renderFileFooter(caption, size, config.width, isError);
  2074. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2075. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2076. if (cat === 'text' || cat === 'html') {
  2077. sText = cat === 'text' ? htmlEncode(data) : data;
  2078. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  2079. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2080. .replace(/\{frameClass}/g, css).replace(/\{cat}/g, ftype)
  2081. .replace(/\{footer}/g, footer).replace(/\{fileindex}/g, ind)
  2082. .replace(/\{data}/g, sText).replace(/\{template}/g, cat);
  2083. } else {
  2084. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  2085. .replace(/\{frameClass}/g, css).replace(/\{type}/g, ftype).replace(/\{fileindex}/g, ind)
  2086. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2087. .replace(/\{footer}/g, footer).replace(/\{data}/g, data).replace(/\{template}/g, cat);
  2088. }
  2089. return content;
  2090. },
  2091. _previewDefault: function (file, previewId, isDisabled) {
  2092. var self = this, $preview = self.$preview, $previewLive = $preview.find('.file-live-thumbs');
  2093. if (!self.showPreview) {
  2094. return;
  2095. }
  2096. var fname = file ? file.name : '', ftype = file ? file.type : '', content,
  2097. isError = isDisabled === true && !self.isUploadable, data = objUrl.createObjectURL(file);
  2098. self._clearDefaultPreview();
  2099. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, file.size);
  2100. if (!$previewLive.length) {
  2101. $previewLive = $(document.createElement('div')).addClass('file-live-thumbs').appendTo($preview);
  2102. }
  2103. $previewLive.append("\n" + content);
  2104. if (isDisabled === true && self.isUploadable) {
  2105. self._setThumbStatus($('#' + previewId), 'Error');
  2106. }
  2107. },
  2108. _previewFile: function (i, file, theFile, previewId, data) {
  2109. if (!this.showPreview) {
  2110. return;
  2111. }
  2112. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  2113. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview,
  2114. chkTypes = types && types.indexOf(cat) >= 0, $previewLive = $preview.find('.file-live-thumbs'),
  2115. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content,
  2116. chkMimes = mimes && mimes.indexOf(file.type) !== -1;
  2117. if (!$previewLive.length) {
  2118. $previewLive = $(document.createElement('div')).addClass('file-live-thumbs').appendTo($preview);
  2119. }
  2120. /** @namespace window.DOMPurify */
  2121. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2122. iData = window.DOMPurify.sanitize(iData);
  2123. }
  2124. if (chkTypes || chkMimes) {
  2125. content = self._generatePreviewTemplate(cat, iData, fname, file.type, previewId, false, file.size);
  2126. self._clearDefaultPreview();
  2127. $previewLive.append("\n" + content);
  2128. self._validateImage(i, previewId, caption, file.type);
  2129. } else {
  2130. self._previewDefault(file, previewId);
  2131. }
  2132. self._initSortable();
  2133. },
  2134. _slugDefault: function (text) {
  2135. return isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2136. },
  2137. _readFiles: function (files) {
  2138. this.reader = new FileReader();
  2139. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2140. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2141. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2142. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2143. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2144. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2145. throwError = function (msg, file, previewId, index) {
  2146. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2147. p2 = {id: previewId, index: index, file: file, files: files};
  2148. self._previewDefault(file, previewId, true);
  2149. if (self.isUploadable) {
  2150. self.addToStack(undefined);
  2151. }
  2152. setTimeout(function () {
  2153. readFile(index + 1);
  2154. }, 100);
  2155. self._initFileActions();
  2156. if (self.removeFromPreviewOnError) {
  2157. $('#' + previewId).remove();
  2158. }
  2159. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2160. };
  2161. self.loadedImages = [];
  2162. self.totalImagesCount = 0;
  2163. $.each(files, function (key, file) {
  2164. var func = self.fileTypeSettings.image || defaultFileTypeSettings.image;
  2165. if (func && func(file.type)) {
  2166. self.totalImagesCount++;
  2167. }
  2168. });
  2169. readFile = function (i) {
  2170. if (isEmpty($el.attr('multiple'))) {
  2171. numFiles = 1;
  2172. }
  2173. if (i >= numFiles) {
  2174. if (self.isUploadable && self.filestack.length > 0) {
  2175. self._raise('filebatchselected', [self.getFileStack()]);
  2176. } else {
  2177. self._raise('filebatchselected', [files]);
  2178. }
  2179. $container.removeClass('file-thumb-loading');
  2180. $status.html('');
  2181. return;
  2182. }
  2183. var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i],
  2184. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  2185. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  2186. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  2187. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  2188. if (!isEmpty(fileExt)) {
  2189. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2190. }
  2191. fileSize = fileSize.toFixed(2);
  2192. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2193. msg = self.msgSizeTooLarge.replace('{name}', caption)
  2194. .replace('{size}', fileSize)
  2195. .replace('{maxSize}', self.maxFileSize);
  2196. self.isError = throwError(msg, file, previewId, i);
  2197. return;
  2198. }
  2199. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  2200. for (j = 0; j < fileTypes.length; j += 1) {
  2201. typ = fileTypes[j];
  2202. checkFile = settings[typ];
  2203. chk = (checkFile !== undefined && checkFile(file.type, caption));
  2204. fileCount += isEmpty(chk) ? 0 : chk.length;
  2205. }
  2206. if (fileCount === 0) {
  2207. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2208. self.isError = throwError(msg, file, previewId, i);
  2209. return;
  2210. }
  2211. }
  2212. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  2213. chk = compare(caption, fileExtExpr);
  2214. fileCount += isEmpty(chk) ? 0 : chk.length;
  2215. if (fileCount === 0) {
  2216. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  2217. strExt);
  2218. self.isError = throwError(msg, file, previewId, i);
  2219. return;
  2220. }
  2221. }
  2222. if (!self.showPreview) {
  2223. self.addToStack(file);
  2224. setTimeout(function () {
  2225. readFile(i + 1);
  2226. }, 100);
  2227. self._raise('fileloaded', [file, previewId, i, reader]);
  2228. return;
  2229. }
  2230. if (!canPreview && fileSize > maxPreviewSize) {
  2231. self.addToStack(file);
  2232. $container.addClass('file-thumb-loading');
  2233. self._previewDefault(file, previewId);
  2234. self._initFileActions();
  2235. self._updateFileDetails(numFiles);
  2236. readFile(i + 1);
  2237. return;
  2238. }
  2239. if ($preview.length && FileReader !== undefined) {
  2240. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2241. $container.addClass('file-thumb-loading');
  2242. reader.onerror = function (evt) {
  2243. self._errorHandler(evt, caption);
  2244. };
  2245. reader.onload = function (theFile) {
  2246. self._previewFile(i, file, theFile, previewId, previewData);
  2247. self._initFileActions();
  2248. };
  2249. reader.onloadend = function () {
  2250. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2251. .replace('{percent}', 50).replace('{name}', caption);
  2252. setTimeout(function () {
  2253. $status.html(msg);
  2254. self._updateFileDetails(numFiles);
  2255. readFile(i + 1);
  2256. }, 100);
  2257. self._raise('fileloaded', [file, previewId, i, reader]);
  2258. };
  2259. reader.onprogress = function (data) {
  2260. if (data.lengthComputable) {
  2261. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2262. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2263. .replace('{percent}', progress).replace('{name}', caption);
  2264. setTimeout(function () {
  2265. $status.html(msg);
  2266. }, 100);
  2267. }
  2268. };
  2269. isText = ifSet('text', settings, defaultFileTypeSettings.text);
  2270. isImage = ifSet('image', settings, defaultFileTypeSettings.image);
  2271. if (isText(file.type, caption)) {
  2272. reader.readAsText(file, self.textEncoding);
  2273. } else {
  2274. if (isImage(file.type, caption)) {
  2275. reader.readAsDataURL(file);
  2276. } else {
  2277. reader.readAsArrayBuffer(file);
  2278. }
  2279. }
  2280. } else {
  2281. self._previewDefault(file, previewId);
  2282. setTimeout(function () {
  2283. readFile(i + 1);
  2284. self._updateFileDetails(numFiles);
  2285. }, 100);
  2286. self._raise('fileloaded', [file, previewId, i, reader]);
  2287. }
  2288. self.addToStack(file);
  2289. };
  2290. readFile(0);
  2291. self._updateFileDetails(numFiles, false);
  2292. },
  2293. _updateFileDetails: function (numFiles) {
  2294. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2295. name = (isIE(9) && findFileName($el.val())) ||
  2296. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2297. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2298. nFiles = previewCache.count(self.id) + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  2299. if (self.isError) {
  2300. self.$previewContainer.removeClass('file-thumb-loading');
  2301. self.$previewStatus.html('');
  2302. self.$captionContainer.find('.kv-caption-icon').hide();
  2303. } else {
  2304. self._showFileIcon();
  2305. }
  2306. self._setCaption(log, self.isError);
  2307. self.$container.removeClass('file-input-new file-input-ajax-new');
  2308. if (arguments.length === 1) {
  2309. self._raise('fileselect', [numFiles, label]);
  2310. }
  2311. if (previewCache.count(self.id)) {
  2312. self._initPreviewActions();
  2313. }
  2314. },
  2315. _setThumbStatus: function ($thumb, status) {
  2316. var self = this;
  2317. if (!self.showPreview) {
  2318. return;
  2319. }
  2320. var icon = 'indicator' + status, msg = icon + 'Title',
  2321. css = 'file-preview-' + status.toLowerCase(),
  2322. $indicator = $thumb.find('.file-upload-indicator'),
  2323. config = self.fileActionSettings;
  2324. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  2325. if (status === 'Error') {
  2326. $thumb.find('.kv-file-upload').attr('disabled', true);
  2327. }
  2328. if (status === 'Success') {
  2329. $thumb.find('.file-drag-handle').remove();
  2330. $indicator.css('margin-left', 0);
  2331. }
  2332. $indicator.html(config[icon]);
  2333. $indicator.attr('title', config[msg]);
  2334. $thumb.addClass(css);
  2335. },
  2336. _setProgressCancelled: function () {
  2337. var self = this;
  2338. self._setProgress(101, self.$progress, self.msgCancelled);
  2339. },
  2340. _setProgress: function (p, $el, error) {
  2341. var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate :
  2342. (error ? self.progressErrorTemplate : (p <= 100 ? self.progressTemplate : self.progressCompleteTemplate)),
  2343. pctLimit = self.progressUploadThreshold;
  2344. $el = $el || self.$progress;
  2345. if (!isEmpty(template)) {
  2346. if (pctLimit && pct > pctLimit && p <= 100) {
  2347. var out = template.replace('{percent}', pctLimit).replace('{percent}', pctLimit).replace('{percent}%', self.msgUploadThreshold);
  2348. $el.html(out);
  2349. } else {
  2350. $el.html(template.replace(/\{percent}/g, pct));
  2351. }
  2352. if (error) {
  2353. $el.find('[role="progressbar"]').html(error);
  2354. }
  2355. }
  2356. },
  2357. _setFileDropZoneTitle: function () {
  2358. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  2359. if (self.isClickable) {
  2360. strFiles = isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  2361. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  2362. }
  2363. $zone.find('.' + self.dropZoneTitleClass).remove();
  2364. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  2365. return;
  2366. }
  2367. if ($zone.find('.file-preview-frame').length === 0 && isEmpty(self.defaultPreviewContent)) {
  2368. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  2369. }
  2370. self.$container.removeClass('file-input-new');
  2371. addCss(self.$container, 'file-input-ajax-new');
  2372. },
  2373. _setAsyncUploadStatus: function (previewId, pct, total) {
  2374. var self = this, sum = 0;
  2375. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  2376. self.uploadStatus[previewId] = pct;
  2377. $.each(self.uploadStatus, function (key, value) {
  2378. sum += value;
  2379. });
  2380. self._setProgress(Math.floor(sum / total));
  2381. },
  2382. _validateMinCount: function () {
  2383. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2384. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  2385. self._noFilesError({});
  2386. return false;
  2387. }
  2388. return true;
  2389. },
  2390. _getFileCount: function (fileCount) {
  2391. var self = this, addCount = 0;
  2392. if (self.validateInitialCount && !self.overwriteInitial) {
  2393. addCount = previewCache.count(self.id);
  2394. fileCount += addCount;
  2395. }
  2396. return fileCount;
  2397. },
  2398. _getFileName: function (file) {
  2399. return file && file.name ? this.slug(file.name) : undefined;
  2400. },
  2401. _getFileNames: function (skipNull) {
  2402. var self = this;
  2403. return self.filenames.filter(function (n) {
  2404. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2405. });
  2406. },
  2407. _setPreviewError: function ($thumb, i, val) {
  2408. var self = this;
  2409. if (i !== undefined) {
  2410. self.updateStack(i, val);
  2411. }
  2412. if (self.removeFromPreviewOnError) {
  2413. $thumb.remove();
  2414. } else {
  2415. self._setThumbStatus($thumb, 'Error');
  2416. }
  2417. },
  2418. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2419. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  2420. $imgEl, isValid;
  2421. if (isEmpty(limit) || !$img.length) {
  2422. return;
  2423. }
  2424. $imgEl = $img[0];
  2425. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2426. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2427. if (isValid) {
  2428. return;
  2429. }
  2430. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2431. self._showUploadError(msg, params);
  2432. self._setPreviewError($thumb, i, null);
  2433. },
  2434. _validateImage: function (i, previewId, fname, ftype) {
  2435. var self = this, $preview = self.$preview, params, w1, w2,
  2436. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  2437. fname = fname || 'Untitled';
  2438. if (!$img.length) {
  2439. return;
  2440. }
  2441. handler($img, 'load', function () {
  2442. w1 = $thumb.width();
  2443. w2 = $preview.width();
  2444. if (w1 > w2) {
  2445. $img.css('width', '100%');
  2446. $thumb.css('width', '97%');
  2447. }
  2448. params = {ind: i, id: previewId};
  2449. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2450. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2451. if (!self.resizeImage) {
  2452. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2453. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2454. }
  2455. self._raise('fileimageloaded', [previewId]);
  2456. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2457. self._validateAllImages();
  2458. objUrl.revokeObjectURL($img.attr('src'));
  2459. });
  2460. },
  2461. _validateAllImages: function () {
  2462. var self = this, i, config, $img, $thumb, pid, ind, params = {}, errFunc;
  2463. if (self.loadedImages.length !== self.totalImagesCount) {
  2464. return;
  2465. }
  2466. self._raise('fileimagesloaded');
  2467. if (!self.resizeImage) {
  2468. return;
  2469. }
  2470. errFunc = self.isUploadable ? self._showUploadError : self._showError;
  2471. for (i = 0; i < self.loadedImages.length; i++) {
  2472. config = self.loadedImages[i];
  2473. $img = config.img;
  2474. $thumb = config.thumb;
  2475. pid = config.pid;
  2476. ind = config.ind;
  2477. params = {id: pid, 'index': ind};
  2478. if (!self._getResizedImage($img[0], config.typ, pid, ind)) {
  2479. errFunc(self.msgImageResizeError, params, 'fileimageresizeerror');
  2480. self._setPreviewError($thumb, ind);
  2481. }
  2482. }
  2483. self._raise('fileimagesresized');
  2484. },
  2485. _getResizedImage: function (image, type, pid, ind) {
  2486. var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1,
  2487. maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2488. isValidImage = (width && height), chkWidth, chkHeight,
  2489. canvas = self.imageCanvas, context = self.imageCanvasContext;
  2490. if (!isValidImage) {
  2491. return false;
  2492. }
  2493. if (width === maxWidth && height === maxHeight) {
  2494. return true;
  2495. }
  2496. type = type || self.resizeDefaultImageType;
  2497. chkWidth = width > maxWidth;
  2498. chkHeight = height > maxHeight;
  2499. if (self.resizePreference === 'width') {
  2500. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2501. } else {
  2502. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2503. }
  2504. self._resetCanvas();
  2505. width *= ratio;
  2506. height *= ratio;
  2507. canvas.width = width;
  2508. canvas.height = height;
  2509. try {
  2510. context.drawImage(image, 0, 0, width, height);
  2511. canvas.toBlob(function (blob) {
  2512. self._raise('fileimageresized', [pid, ind]);
  2513. self.filestack[ind] = blob;
  2514. }, type, self.resizeQuality);
  2515. return true;
  2516. }
  2517. catch (err) {
  2518. return false;
  2519. }
  2520. },
  2521. _initBrowse: function ($container) {
  2522. var self = this;
  2523. if (self.showBrowse) {
  2524. self.$btnFile = $container.find('.btn-file');
  2525. self.$btnFile.append(self.$element);
  2526. } else {
  2527. self.$element.hide();
  2528. }
  2529. },
  2530. _initCaption: function () {
  2531. var self = this, cap = self.initialCaption || '';
  2532. if (self.overwriteInitial || isEmpty(cap)) {
  2533. self.$caption.html('');
  2534. return false;
  2535. }
  2536. self._setCaption(cap);
  2537. return true;
  2538. },
  2539. _setCaption: function (content, isError) {
  2540. var self = this, title, out, n, cap, stack = self.getFileStack();
  2541. if (!self.$caption.length) {
  2542. return;
  2543. }
  2544. if (isError) {
  2545. title = $('<div>' + self.msgValidationError + '</div>').text();
  2546. n = stack.length;
  2547. if (n) {
  2548. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2549. } else {
  2550. cap = self._getMsgSelected(self.msgNo);
  2551. }
  2552. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2553. (isEmpty(content) ? cap : content) + '</span>';
  2554. } else {
  2555. if (isEmpty(content)) {
  2556. return;
  2557. }
  2558. title = $('<div>' + content + '</div>').text();
  2559. out = self._getLayoutTemplate('fileIcon') + title;
  2560. }
  2561. self.$caption.html(out);
  2562. self.$caption.attr('title', title);
  2563. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2564. },
  2565. _createContainer: function () {
  2566. var self = this, $container = $(document.createElement("div"))
  2567. .attr({"class": 'file-input file-input-new'})
  2568. .html(self._renderMain());
  2569. self.$element.before($container);
  2570. self._initBrowse($container);
  2571. if (self.theme) {
  2572. $container.addClass('theme-' + self.theme);
  2573. }
  2574. return $container;
  2575. },
  2576. _refreshContainer: function () {
  2577. var self = this, $container = self.$container;
  2578. $container.before(self.$element);
  2579. $container.html(self._renderMain());
  2580. self._initBrowse($container);
  2581. },
  2582. _renderMain: function () {
  2583. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2584. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  2585. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  2586. .replace(/\{class}/g, self.previewClass)
  2587. .replace(/\{dropClass}/g, dropCss),
  2588. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2589. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2590. return self.mainTemplate.replace(/\{class}/g, self.mainClass +
  2591. (!self.showBrowse && self.showCaption ? ' no-browse' : ''))
  2592. .replace(/\{preview}/g, preview)
  2593. .replace(/\{close}/g, close)
  2594. .replace(/\{caption}/g, caption)
  2595. .replace(/\{upload}/g, self._renderButton('upload'))
  2596. .replace(/\{remove}/g, self._renderButton('remove'))
  2597. .replace(/\{cancel}/g, self._renderButton('cancel'))
  2598. .replace(/\{browse}/g, self._renderButton('browse'));
  2599. },
  2600. _renderButton: function (type) {
  2601. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2602. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2603. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2604. switch (type) {
  2605. case 'remove':
  2606. if (!self.showRemove) {
  2607. return '';
  2608. }
  2609. break;
  2610. case 'cancel':
  2611. if (!self.showCancel) {
  2612. return '';
  2613. }
  2614. css += ' hide';
  2615. break;
  2616. case 'upload':
  2617. if (!self.showUpload) {
  2618. return '';
  2619. }
  2620. if (self.isUploadable && !self.isDisabled) {
  2621. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2622. } else {
  2623. btnType = 'submit';
  2624. }
  2625. break;
  2626. case 'browse':
  2627. if (!self.showBrowse) {
  2628. return '';
  2629. }
  2630. tmplt = self._getLayoutTemplate('btnBrowse');
  2631. break;
  2632. default:
  2633. return '';
  2634. }
  2635. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2636. if (!isEmpty(label)) {
  2637. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2638. }
  2639. return tmplt.replace('{type}', btnType).replace('{css}', css).replace('{title}', title)
  2640. .replace('{status}', status).replace('{icon}', icon).replace('{label}', label);
  2641. },
  2642. _renderThumbProgress: function () {
  2643. return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g,
  2644. '0') + '</div>';
  2645. },
  2646. _renderFileFooter: function (caption, size, width, isError) {
  2647. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  2648. upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'),
  2649. indicator = isError ? config.indicatorError : config.indicatorNew,
  2650. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle;
  2651. size = self._getSize(size);
  2652. if (self.isUploadable) {
  2653. out = template.replace(/\{actions}/g, self._renderFileActions(upl, rem, zoom, drg, false, false, false))
  2654. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2655. .replace(/\{progress}/g, self._renderThumbProgress()).replace(/\{indicator}/g, indicator)
  2656. .replace(/\{indicatorTitle}/g, title);
  2657. } else {
  2658. out = template.replace(/\{actions}/g,
  2659. self._renderFileActions(false, false, zoom, drg, false, false, false))
  2660. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2661. .replace(/\{progress}/g, '').replace(/\{indicator}/g, indicator)
  2662. .replace(/\{indicatorTitle}/g, title);
  2663. }
  2664. out = replaceTags(out, self.previewThumbTags);
  2665. return out;
  2666. },
  2667. _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) {
  2668. if (!showUpload && !showDelete && !showZoom && !showDrag) {
  2669. return '';
  2670. }
  2671. var self = this,
  2672. vUrl = url === false ? '' : ' data-url="' + url + '"',
  2673. vKey = key === false ? '' : ' data-key="' + key + '"',
  2674. btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css,
  2675. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  2676. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  2677. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  2678. if (showDelete) {
  2679. btnDelete = self._getLayoutTemplate('actionDelete')
  2680. .replace(/\{removeClass}/g, removeClass)
  2681. .replace(/\{removeIcon}/g, config.removeIcon)
  2682. .replace(/\{removeTitle}/g, config.removeTitle)
  2683. .replace(/\{dataUrl}/g, vUrl)
  2684. .replace(/\{dataKey}/g, vKey);
  2685. }
  2686. if (showUpload) {
  2687. btnUpload = self._getLayoutTemplate('actionUpload')
  2688. .replace(/\{uploadClass}/g, config.uploadClass)
  2689. .replace(/\{uploadIcon}/g, config.uploadIcon)
  2690. .replace(/\{uploadTitle}/g, config.uploadTitle);
  2691. }
  2692. if (showZoom) {
  2693. btnZoom = self._getLayoutTemplate('actionZoom')
  2694. .replace(/\{zoomClass}/g, config.zoomClass)
  2695. .replace(/\{zoomIcon}/g, config.zoomIcon)
  2696. .replace(/\{zoomTitle}/g, config.zoomTitle);
  2697. }
  2698. if (showDrag && isInit) {
  2699. css = 'drag-handle-init ' + config.dragClass;
  2700. btnDrag = self._getLayoutTemplate('actionDrag').replace(/\{dragClass}/g, css)
  2701. .replace(/\{dragTitle}/g, config.dragTitle)
  2702. .replace(/\{dragIcon}/g, config.dragIcon);
  2703. }
  2704. return template.replace(/\{delete}/g, btnDelete)
  2705. .replace(/\{upload}/g, btnUpload)
  2706. .replace(/\{zoom}/g, btnZoom)
  2707. .replace(/\{drag}/g, btnDrag)
  2708. .replace(/\{other}/g, otherButtons);
  2709. },
  2710. _browse: function (e) {
  2711. var self = this;
  2712. self._raise('filebrowse');
  2713. if (e && e.isDefaultPrevented()) {
  2714. return;
  2715. }
  2716. if (self.isError && !self.isUploadable) {
  2717. self.clear();
  2718. }
  2719. self.$captionContainer.focus();
  2720. },
  2721. _change: function (e) {
  2722. var self = this, $el = self.$element;
  2723. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2724. self.fileInputCleared = false;
  2725. return;
  2726. }
  2727. self.fileInputCleared = false;
  2728. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2729. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2730. isSingleUpload = isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2731. throwError = function (mesg, file, previewId, index) {
  2732. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2733. p2 = {id: previewId, index: index, file: file, files: files};
  2734. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  2735. };
  2736. self.reader = null;
  2737. self._resetUpload();
  2738. self._hideFileIcon();
  2739. if (self.isUploadable) {
  2740. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2741. }
  2742. if (isDragDrop) {
  2743. tfiles = [];
  2744. while (files[i]) {
  2745. f = files[i];
  2746. if (!f.type && f.size % 4096 === 0) {
  2747. folders++;
  2748. } else {
  2749. tfiles.push(f);
  2750. }
  2751. i++;
  2752. }
  2753. } else {
  2754. if (e.target.files === undefined) {
  2755. tfiles = e.target && e.target.value ? [
  2756. {name: e.target.value.replace(/^.+\\/, '')}
  2757. ] : [];
  2758. } else {
  2759. tfiles = e.target.files;
  2760. }
  2761. }
  2762. if (isEmpty(tfiles) || tfiles.length === 0) {
  2763. if (!isAjaxUpload) {
  2764. self.clear();
  2765. }
  2766. self._showFolderError(folders);
  2767. self._raise('fileselectnone');
  2768. return;
  2769. }
  2770. self._resetErrors();
  2771. len = tfiles.length;
  2772. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  2773. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2774. if (!self.autoReplace || len > self.maxFileCount) {
  2775. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2776. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2777. self.isError = throwError(msg, null, null, null);
  2778. self.$captionContainer.find('.kv-caption-icon').hide();
  2779. self._setCaption('', true);
  2780. self.$container.removeClass('file-input-new file-input-ajax-new');
  2781. return;
  2782. }
  2783. if (total > self.maxFileCount) {
  2784. self._resetPreviewThumbs(isAjaxUpload);
  2785. }
  2786. } else {
  2787. if (!isAjaxUpload || flagSingle) {
  2788. self._resetPreviewThumbs(false);
  2789. if (flagSingle) {
  2790. self.clearStack();
  2791. }
  2792. } else {
  2793. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2794. self._resetPreviewThumbs(true);
  2795. }
  2796. }
  2797. }
  2798. if (self.isPreviewable) {
  2799. self._readFiles(tfiles);
  2800. } else {
  2801. self._updateFileDetails(1);
  2802. }
  2803. self._showFolderError(folders);
  2804. },
  2805. _abort: function (params) {
  2806. var self = this, data;
  2807. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  2808. data = $.extend(true, {}, self._getOutData(), params);
  2809. data.abortData = self.ajaxAborted.data || {};
  2810. data.abortMessage = self.ajaxAborted.message;
  2811. self.cancel();
  2812. self._setProgress(101, self.$progress, self.msgCancelled);
  2813. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  2814. return true;
  2815. }
  2816. return false;
  2817. },
  2818. _resetFileStack: function () {
  2819. var self = this, i = 0, newstack = [], newnames = [];
  2820. self._getThumbs().each(function () {
  2821. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  2822. file = self.filestack[ind];
  2823. if (ind === -1) {
  2824. return;
  2825. }
  2826. if (file !== undefined) {
  2827. newstack[i] = file;
  2828. newnames[i] = self._getFileName(file);
  2829. $thumb.attr({
  2830. 'id': self.previewInitId + '-' + i,
  2831. 'data-fileindex': i
  2832. });
  2833. i++;
  2834. } else {
  2835. $thumb.attr({
  2836. 'id': 'uploaded-' + uniqId(),
  2837. 'data-fileindex': '-1'
  2838. });
  2839. }
  2840. });
  2841. self.filestack = newstack;
  2842. self.filenames = newnames;
  2843. },
  2844. clearStack: function () {
  2845. var self = this;
  2846. self.filestack = [];
  2847. self.filenames = [];
  2848. return self.$element;
  2849. },
  2850. updateStack: function (i, file) {
  2851. var self = this;
  2852. self.filestack[i] = file;
  2853. self.filenames[i] = self._getFileName(file);
  2854. return self.$element;
  2855. },
  2856. addToStack: function (file) {
  2857. var self = this;
  2858. self.filestack.push(file);
  2859. self.filenames.push(self._getFileName(file));
  2860. return self.$element;
  2861. },
  2862. getFileStack: function (skipNull) {
  2863. var self = this;
  2864. return self.filestack.filter(function (n) {
  2865. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2866. });
  2867. },
  2868. getFilesCount: function () {
  2869. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2870. return self._getFileCount(len);
  2871. },
  2872. lock: function () {
  2873. var self = this;
  2874. self._resetErrors();
  2875. self.disable();
  2876. if (self.showRemove) {
  2877. addCss(self.$container.find('.fileinput-remove'), 'hide');
  2878. }
  2879. if (self.showCancel) {
  2880. self.$container.find('.fileinput-cancel').removeClass('hide');
  2881. }
  2882. self._raise('filelock', [self.filestack, self._getExtraData()]);
  2883. return self.$element;
  2884. },
  2885. unlock: function (reset) {
  2886. var self = this;
  2887. if (reset === undefined) {
  2888. reset = true;
  2889. }
  2890. self.enable();
  2891. if (self.showCancel) {
  2892. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  2893. }
  2894. if (self.showRemove) {
  2895. self.$container.find('.fileinput-remove').removeClass('hide');
  2896. }
  2897. if (reset) {
  2898. self._resetFileStack();
  2899. }
  2900. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  2901. return self.$element;
  2902. },
  2903. cancel: function () {
  2904. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  2905. if (len > 0) {
  2906. for (i = 0; i < len; i += 1) {
  2907. self.cancelling = true;
  2908. xhr[i].abort();
  2909. }
  2910. }
  2911. self._setProgressCancelled();
  2912. self._getThumbs().each(function () {
  2913. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  2914. $thumb.removeClass('file-uploading');
  2915. if (self.filestack[ind] !== undefined) {
  2916. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  2917. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  2918. }
  2919. self.unlock();
  2920. });
  2921. return self.$element;
  2922. },
  2923. clear: function () {
  2924. var self = this, cap;
  2925. self.$btnUpload.removeAttr('disabled');
  2926. self._getThumbs().find('video,audio,img').each(function () {
  2927. cleanMemory($(this));
  2928. });
  2929. self._resetUpload();
  2930. self.clearStack();
  2931. self._clearFileInput();
  2932. self._resetErrors(true);
  2933. self._raise('fileclear');
  2934. if (self._hasInitialPreview()) {
  2935. self._showFileIcon();
  2936. self._resetPreview();
  2937. self._initPreviewActions();
  2938. self.$container.removeClass('file-input-new');
  2939. } else {
  2940. self._getThumbs().each(function () {
  2941. self._clearObjects($(this));
  2942. });
  2943. if (self.isUploadable) {
  2944. previewCache.data[self.id] = {};
  2945. }
  2946. self.$preview.html('');
  2947. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  2948. self.$caption.html(cap);
  2949. self.$caption.attr('title', '');
  2950. addCss(self.$container, 'file-input-new');
  2951. self._validateDefaultPreview();
  2952. }
  2953. if (self.$container.find('.file-preview-frame').length === 0) {
  2954. if (!self._initCaption()) {
  2955. self.$captionContainer.find('.kv-caption-icon').hide();
  2956. }
  2957. }
  2958. self._hideFileIcon();
  2959. self._raise('filecleared');
  2960. self.$captionContainer.focus();
  2961. self._setFileDropZoneTitle();
  2962. return self.$element;
  2963. },
  2964. reset: function () {
  2965. var self = this;
  2966. self._resetPreview();
  2967. self.$container.find('.fileinput-filename').text('');
  2968. self._raise('filereset');
  2969. addCss(self.$container, 'file-input-new');
  2970. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  2971. self.$container.removeClass('file-input-new');
  2972. }
  2973. self._setFileDropZoneTitle();
  2974. self.clearStack();
  2975. self.formdata = {};
  2976. return self.$element;
  2977. },
  2978. disable: function () {
  2979. var self = this;
  2980. self.isDisabled = true;
  2981. self._raise('filedisabled');
  2982. self.$element.attr('disabled', 'disabled');
  2983. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  2984. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  2985. "disabled",
  2986. true);
  2987. self._initDragDrop();
  2988. return self.$element;
  2989. },
  2990. enable: function () {
  2991. var self = this;
  2992. self.isDisabled = false;
  2993. self._raise('fileenabled');
  2994. self.$element.removeAttr('disabled');
  2995. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  2996. self.$container.find(
  2997. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  2998. self._initDragDrop();
  2999. return self.$element;
  3000. },
  3001. upload: function () {
  3002. var self = this, totLen = self.getFileStack().length, params = {},
  3003. i, outData, len, hasExtraData = !$.isEmptyObject(self._getExtraData());
  3004. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  3005. self._noFilesError(params);
  3006. return;
  3007. }
  3008. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  3009. return;
  3010. }
  3011. self._resetUpload();
  3012. self.$progress.removeClass('hide');
  3013. self.uploadCount = 0;
  3014. self.uploadStatus = {};
  3015. self.uploadLog = [];
  3016. self.lock();
  3017. self._setProgress(2);
  3018. if (totLen === 0 && hasExtraData) {
  3019. self._uploadExtraOnly();
  3020. return;
  3021. }
  3022. len = self.filestack.length;
  3023. self.hasInitData = false;
  3024. if (self.uploadAsync) {
  3025. outData = self._getOutData();
  3026. self._raise('filebatchpreupload', [outData]);
  3027. self.fileBatchCompleted = false;
  3028. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3029. self.uploadAsyncCount = self.getFileStack().length;
  3030. for (i = 0; i < len; i++) {
  3031. self.uploadCache.content[i] = null;
  3032. self.uploadCache.config[i] = null;
  3033. self.uploadCache.tags[i] = null;
  3034. }
  3035. for (i = 0; i < len; i++) {
  3036. if (self.filestack[i] !== undefined) {
  3037. self._uploadSingle(i, self.filestack, true);
  3038. }
  3039. }
  3040. return;
  3041. }
  3042. self._uploadBatch();
  3043. return self.$element;
  3044. },
  3045. destroy: function () {
  3046. var self = this, $cont = self.$container;
  3047. $cont.find('.file-drop-zone').off();
  3048. self.$element.insertBefore($cont).off(NAMESPACE).removeData();
  3049. $cont.off().remove();
  3050. return self.$element;
  3051. },
  3052. refresh: function (options) {
  3053. var self = this, $el = self.$element;
  3054. options = options ? $.extend(true, {}, self.options, options) : self.options;
  3055. self.destroy();
  3056. $el.fileinput(options);
  3057. if ($el.val()) {
  3058. $el.trigger('change.fileinput');
  3059. }
  3060. return $el;
  3061. }
  3062. };
  3063. $.fn.fileinput = function (option) {
  3064. if (!hasFileAPISupport() && !isIE(9)) {
  3065. return;
  3066. }
  3067. var args = Array.apply(null, arguments), retvals = [];
  3068. args.shift();
  3069. this.each(function () {
  3070. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  3071. theme = options.theme || self.data('theme'), l = {}, t = {},
  3072. lang = options.language || self.data('language') || 'en', opts;
  3073. if (!data) {
  3074. if (theme) {
  3075. t = $.fn.fileinputThemes[theme] || {};
  3076. }
  3077. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  3078. l = $.fn.fileinputLocales[lang] || {};
  3079. }
  3080. opts = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options,
  3081. self.data());
  3082. data = new FileInput(this, opts);
  3083. self.data('fileinput', data);
  3084. }
  3085. if (typeof option === 'string') {
  3086. retvals.push(data[option].apply(data, args));
  3087. }
  3088. });
  3089. switch (retvals.length) {
  3090. case 0:
  3091. return this;
  3092. case 1:
  3093. return retvals[0];
  3094. default:
  3095. return retvals;
  3096. }
  3097. };
  3098. $.fn.fileinput.defaults = {
  3099. language: 'en',
  3100. showCaption: true,
  3101. showBrowse: true,
  3102. showPreview: true,
  3103. showRemove: true,
  3104. showUpload: true,
  3105. showCancel: true,
  3106. showClose: true,
  3107. showUploadedThumbs: true,
  3108. browseOnZoneClick: false,
  3109. autoReplace: false,
  3110. previewClass: '',
  3111. captionClass: '',
  3112. mainClass: 'file-caption-main',
  3113. mainTemplate: null,
  3114. purifyHtml: true,
  3115. fileSizeGetter: null,
  3116. initialCaption: '',
  3117. initialPreview: [],
  3118. initialPreviewDelimiter: '*$$*',
  3119. initialPreviewAsData: false,
  3120. initialPreviewFileType: 'image',
  3121. initialPreviewConfig: [],
  3122. initialPreviewThumbTags: [],
  3123. previewThumbTags: {},
  3124. initialPreviewShowDelete: true,
  3125. removeFromPreviewOnError: false,
  3126. deleteUrl: '',
  3127. deleteExtraData: {},
  3128. overwriteInitial: true,
  3129. layoutTemplates: defaultLayoutTemplates,
  3130. previewTemplates: defaultPreviewTemplates,
  3131. previewZoomSettings: defaultPreviewZoomSettings,
  3132. previewZoomButtonIcons: {
  3133. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  3134. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  3135. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  3136. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  3137. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  3138. close: '<i class="glyphicon glyphicon-remove"></i>'
  3139. },
  3140. previewZoomButtonClasses: {
  3141. prev: 'btn btn-navigate',
  3142. next: 'btn btn-navigate',
  3143. toggleheader: 'btn btn-default btn-header-toggle',
  3144. fullscreen: 'btn btn-default',
  3145. borderless: 'btn btn-default',
  3146. close: 'btn btn-default'
  3147. },
  3148. allowedPreviewTypes: defaultPreviewTypes,
  3149. allowedPreviewMimeTypes: null,
  3150. allowedFileTypes: null,
  3151. allowedFileExtensions: null,
  3152. defaultPreviewContent: null,
  3153. customLayoutTags: {},
  3154. customPreviewTags: {},
  3155. previewSettings: defaultPreviewSettings,
  3156. fileTypeSettings: defaultFileTypeSettings,
  3157. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  3158. previewFileIconClass: 'file-other-icon',
  3159. previewFileIconSettings: {},
  3160. previewFileExtSettings: {},
  3161. buttonLabelClass: 'hidden-xs',
  3162. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  3163. browseClass: 'btn btn-primary',
  3164. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  3165. removeClass: 'btn btn-default',
  3166. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  3167. cancelClass: 'btn btn-default',
  3168. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  3169. uploadClass: 'btn btn-default',
  3170. uploadUrl: null,
  3171. uploadAsync: true,
  3172. uploadExtraData: {},
  3173. zoomModalHeight: 480,
  3174. minImageWidth: null,
  3175. minImageHeight: null,
  3176. maxImageWidth: null,
  3177. maxImageHeight: null,
  3178. resizeImage: false,
  3179. resizePreference: 'width',
  3180. resizeQuality: 0.92,
  3181. resizeDefaultImageType: 'image/jpeg',
  3182. maxFileSize: 0,
  3183. maxFilePreviewSize: 25600, // 25 MB
  3184. minFileCount: 0,
  3185. maxFileCount: 0,
  3186. validateInitialCount: false,
  3187. msgValidationErrorClass: 'text-danger',
  3188. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  3189. msgErrorClass: 'file-error-message',
  3190. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  3191. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  3192. progressCompleteClass: "progress-bar progress-bar-success",
  3193. progressErrorClass: "progress-bar progress-bar-danger",
  3194. progressUploadThreshold: 99,
  3195. previewFileType: 'image',
  3196. elCaptionContainer: null,
  3197. elCaptionText: null,
  3198. elPreviewContainer: null,
  3199. elPreviewImage: null,
  3200. elPreviewStatus: null,
  3201. elErrorContainer: null,
  3202. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  3203. slugCallback: null,
  3204. dropZoneEnabled: true,
  3205. dropZoneTitleClass: 'file-drop-zone-title',
  3206. fileActionSettings: {},
  3207. otherActionButtons: '',
  3208. textEncoding: 'UTF-8',
  3209. ajaxSettings: {},
  3210. ajaxDeleteSettings: {},
  3211. showAjaxErrorDetails: true
  3212. };
  3213. $.fn.fileinputLocales.en = {
  3214. fileSingle: 'file',
  3215. filePlural: 'files',
  3216. browseLabel: 'Browse &hellip;',
  3217. removeLabel: 'Remove',
  3218. removeTitle: 'Clear selected files',
  3219. cancelLabel: 'Cancel',
  3220. cancelTitle: 'Abort ongoing upload',
  3221. uploadLabel: 'Upload',
  3222. uploadTitle: 'Upload selected files',
  3223. msgNo: 'No',
  3224. msgNoFilesSelected: 'No files selected',
  3225. msgCancelled: 'Cancelled',
  3226. msgZoomModalHeading: 'Detailed Preview',
  3227. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  3228. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  3229. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  3230. msgFileNotFound: 'File "{name}" not found!',
  3231. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  3232. msgFileNotReadable: 'File "{name}" is not readable.',
  3233. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  3234. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  3235. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  3236. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  3237. msgUploadAborted: 'The file upload was aborted',
  3238. msgUploadThreshold: 'Processing...',
  3239. msgValidationError: 'Validation Error',
  3240. msgLoading: 'Loading file {index} of {files} &hellip;',
  3241. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  3242. msgSelected: '{n} {files} selected',
  3243. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  3244. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  3245. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  3246. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  3247. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  3248. msgImageResizeError: 'Could not get the image dimensions to resize.',
  3249. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  3250. dropZoneTitle: 'Drag & drop files here &hellip;',
  3251. dropZoneClickTitle: '<br>(or click to select {files})',
  3252. previewZoomButtonTitles: {
  3253. prev: 'View previous file',
  3254. next: 'View next file',
  3255. toggleheader: 'Toggle header',
  3256. fullscreen: 'Toggle full screen',
  3257. borderless: 'Toggle borderless mode',
  3258. close: 'Close detailed preview'
  3259. }
  3260. };
  3261. $.fn.fileinput.Constructor = FileInput;
  3262. /**
  3263. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  3264. */
  3265. $(document).ready(function () {
  3266. var $input = $('input.file[type=file]');
  3267. if ($input.length) {
  3268. $input.fileinput();
  3269. }
  3270. });
  3271. }));