fileinput.js 152 KB

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