fileinput.js 158 KB

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