fileinput.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.1.8
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API.
  7. *
  8. * The plugin drastically enhances the HTML file input to preview multiple files on the client before
  9. * upload. In addition it provides the ability to preview content of images, text, videos, audio, html,
  10. * flash and other objects. It also offers the ability to upload and delete files using AJAX, and add
  11. * files in batches (i.e. preview, append, or remove before upload).
  12. *
  13. * Author: Kartik Visweswaran
  14. * Copyright: 2015, Kartik Visweswaran, Krajee.com
  15. * For more JQuery plugins visit http://plugins.krajee.com
  16. * For more Yii related demos visit http://demos.krajee.com
  17. */
  18. (function ($) {
  19. "use strict";
  20. String.prototype.repl = function (from, to) {
  21. return this.split(from).join(to);
  22. };
  23. var isIE = function (ver) {
  24. var div = document.createElement("div"), status;
  25. div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->";
  26. status = (div.getElementsByTagName("i").length === 1);
  27. document.body.appendChild(div);
  28. div.parentNode.removeChild(div);
  29. return status;
  30. },
  31. previewCache = {
  32. data: {},
  33. init: function (obj) {
  34. var content = obj.initialPreview, config = obj.initialPreviewConfig, id = obj.id;
  35. if (content.length > 0 && !isArray(content)) {
  36. content = content.split(obj.initialPreviewDelimiter);
  37. }
  38. previewCache.data[id] = {
  39. content: content,
  40. config: config,
  41. delimiter: obj.initialPreviewDelimiter,
  42. template: obj.previewGenericTemplate,
  43. msg: obj.msgSelected,
  44. initId: obj.previewInitId,
  45. footer: obj.getLayoutTemplate('footer'),
  46. isDelete: obj.initialPreviewShowDelete,
  47. caption: obj.initialCaption,
  48. actions: function (showUpload, showDelete, disabled, url, key, index) {
  49. return obj.renderFileActions(showUpload, showDelete, disabled, url, key, index);
  50. }
  51. };
  52. },
  53. fetch: function (id) {
  54. return previewCache.data[id].content.filter(function (n) {
  55. return n !== undefined;
  56. });
  57. },
  58. count: function (id) {
  59. return !!previewCache.data[id] && !!previewCache.data[id].content ? previewCache.fetch(id).length : 0;
  60. },
  61. get: function (id, i, isDisabled) {
  62. var ind = 'init_' + i, data = previewCache.data[id],
  63. previewId = data.initId + '-' + ind;
  64. isDisabled = isDisabled === undefined ? true : isDisabled;
  65. if (data.content[i] === undefined) {
  66. return '';
  67. }
  68. return data.template
  69. .repl('{previewId}', previewId)
  70. .repl('{frameClass}', ' file-preview-initial')
  71. .repl('{fileindex}', ind)
  72. .repl('{content}', data.content[i])
  73. .repl('{footer}', previewCache.footer(id, i, isDisabled));
  74. },
  75. add: function (id, content, config, append) {
  76. var data = $.extend(true, {}, previewCache.data[id]), index;
  77. if (!isArray(content)) {
  78. content = content.split(data.delimiter);
  79. }
  80. if (append) {
  81. index = data.content.push(content) - 1;
  82. data.config[index] = config;
  83. } else {
  84. index = content.length;
  85. data.content = content;
  86. data.config = config;
  87. }
  88. previewCache.data[id] = data;
  89. return index;
  90. },
  91. set: function (id, content, config, append) {
  92. var data = $.extend(true, {}, previewCache.data[id]), i;
  93. if (!isArray(content)) {
  94. content = content.split(data.delimiter);
  95. }
  96. if (append) {
  97. for (i = 0; i < content.length; i++) {
  98. data.content.push(content[i]);
  99. }
  100. for (i = 0; i < config.length; i++) {
  101. data.config.push(config[i]);
  102. }
  103. } else {
  104. data.content = content;
  105. data.config = config;
  106. }
  107. previewCache.data[id] = data;
  108. },
  109. unset: function (id, index) {
  110. var chk = previewCache.count(id);
  111. if (!chk) {
  112. return;
  113. }
  114. if (chk === 1) {
  115. previewCache.data[id].content = [];
  116. previewCache.data[id].config = [];
  117. return;
  118. }
  119. previewCache.data[id].content[index] = undefined;
  120. previewCache.data[id].config[index] = undefined;
  121. },
  122. out: function (id) {
  123. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id);
  124. if (len === 0) {
  125. return {content: '', caption: ''};
  126. }
  127. for (var i = 0; i < len; i++) {
  128. html += previewCache.get(id, i);
  129. }
  130. caption = data.msg.repl('{n}', len);
  131. return {content: html, caption: caption};
  132. },
  133. footer: function (id, i, isDisabled) {
  134. var data = previewCache.data[id];
  135. isDisabled = isDisabled === undefined ? true : isDisabled;
  136. if (data.config.length === 0 || isEmpty(data.config[i])) {
  137. return '';
  138. }
  139. var config = data.config[i],
  140. caption = isSet('caption', config) ? config.caption : '',
  141. width = isSet('width', config) ? config.width : 'auto',
  142. url = isSet('url', config) ? config.url : false,
  143. key = isSet('key', config) ? config.key : null,
  144. disabled = (url === false) && isDisabled,
  145. actions = data.isDelete ? data.actions(false, true, disabled, url, key, i) : '',
  146. footer = data.footer.repl('{actions}', actions);
  147. return footer
  148. .repl('{caption}', caption)
  149. .repl('{width}', width)
  150. .repl('{indicator}', '')
  151. .repl('{indicatorTitle}', '');
  152. }
  153. },
  154. PREVIEW_FRAMES = '.file-preview-frame:not(.file-preview-initial)',
  155. getNum = function (num, def) {
  156. def = def || 0;
  157. if (typeof num === "number") {
  158. return num;
  159. }
  160. if (typeof num === "string") {
  161. num = parseFloat(num);
  162. }
  163. return isNaN(num) ? def : num;
  164. },
  165. hasFileAPISupport = function () {
  166. return window.File && window.FileReader;
  167. },
  168. hasDragDropSupport = function () {
  169. var $div = document.createElement('div');
  170. return !isIE(9) && ($div.draggable !== undefined || ($div.ondragstart !== undefined && $div.ondrop !== undefined));
  171. },
  172. hasFileUploadSupport = function () {
  173. return hasFileAPISupport && window.FormData;
  174. },
  175. addCss = function ($el, css) {
  176. $el.removeClass(css).addClass(css);
  177. },
  178. STYLE_SETTING = 'style="width:{width};height:{height};"',
  179. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  180. ' <param name="allowFullScreen" value="true" />\n' +
  181. ' <param name="allowScriptAccess" value="always" />\n' +
  182. ' <param name="autoPlay" value="false" />\n' +
  183. ' <param name="autoStart" value="false" />\n' +
  184. ' <param name="quality" value="high" />\n',
  185. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  186. ' {previewFileIcon}\n' +
  187. ' </div>',
  188. defaultFileActionSettings = {
  189. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  190. removeClass: 'btn btn-xs btn-default',
  191. removeTitle: 'Remove file',
  192. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  193. uploadClass: 'btn btn-xs btn-default',
  194. uploadTitle: 'Upload file',
  195. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  196. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>',
  197. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  198. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  199. indicatorNewTitle: 'Not uploaded yet',
  200. indicatorSuccessTitle: 'Uploaded',
  201. indicatorErrorTitle: 'Upload Error',
  202. indicatorLoadingTitle: 'Uploading ...'
  203. },
  204. tMain1 = '{preview}\n' +
  205. '<div class="kv-upload-progress hide"></div>\n' +
  206. '<div class="input-group {class}">\n' +
  207. ' {caption}\n' +
  208. ' <div class="input-group-btn">\n' +
  209. ' {remove}\n' +
  210. ' {cancel}\n' +
  211. ' {upload}\n' +
  212. ' {browse}\n' +
  213. ' </div>\n' +
  214. '</div>',
  215. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  216. tPreview = '<div class="file-preview {class}">\n' +
  217. ' <div class="close fileinput-remove">&times;</div>\n' +
  218. ' <div class="{dropClass}">\n' +
  219. ' <div class="file-preview-thumbnails">\n' +
  220. ' </div>\n' +
  221. ' <div class="clearfix"></div>' +
  222. ' <div class="file-preview-status text-center text-success"></div>\n' +
  223. ' <div class="kv-fileinput-error"></div>\n' +
  224. ' </div>\n' +
  225. '</div>',
  226. tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  227. tCaption = '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  228. ' <span class="file-caption-ellipsis">&hellip;</span>\n' +
  229. ' <div class="file-caption-name"></div>\n' +
  230. '</div>',
  231. tModal = '<div id="{id}" class="modal fade">\n' +
  232. ' <div class="modal-dialog modal-lg">\n' +
  233. ' <div class="modal-content">\n' +
  234. ' <div class="modal-header">\n' +
  235. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  236. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  237. ' </div>\n' +
  238. ' <div class="modal-body">\n' +
  239. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  240. ' </div>\n' +
  241. ' </div>\n' +
  242. ' </div>\n' +
  243. '</div>',
  244. tProgress = '<div class="progress">\n' +
  245. ' <div class="{class}" role="progressbar"' +
  246. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  247. ' {percent}%\n' +
  248. ' </div>\n' +
  249. '</div>',
  250. tFooter = '<div class="file-thumbnail-footer">\n' +
  251. ' <div class="file-caption-name">{caption}</div>\n' +
  252. ' {actions}\n' +
  253. '</div>',
  254. tActions = '<div class="file-actions">\n' +
  255. ' <div class="file-footer-buttons">\n' +
  256. ' {upload}{delete}{other}' +
  257. ' </div>\n' +
  258. ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
  259. ' <div class="clearfix"></div>\n' +
  260. '</div>',
  261. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  262. 'title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  263. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  264. ' {uploadIcon}\n</button>\n',
  265. tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  266. ' {content}\n' +
  267. ' {footer}\n' +
  268. '</div>\n',
  269. tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  270. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  271. ' ' + DEFAULT_PREVIEW + '\n' +
  272. ' </object>\n' +
  273. ' {footer}\n' +
  274. '</div>',
  275. tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  276. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  277. ' {footer}\n' +
  278. '</div>\n',
  279. tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  280. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  281. ' {data}\n' +
  282. ' </div>\n' +
  283. ' {footer}\n' +
  284. '</div>',
  285. tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  286. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  287. ' <video width="{width}" height="{height}" controls>\n' +
  288. ' <source src="{data}" type="{type}">\n' +
  289. ' ' + DEFAULT_PREVIEW + '\n' +
  290. ' </video>\n' +
  291. ' {footer}\n' +
  292. '</div>\n',
  293. tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  294. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  295. ' <audio controls>\n' +
  296. ' <source src="' + '{data}' + '" type="{type}">\n' +
  297. ' ' + DEFAULT_PREVIEW + '\n' +
  298. ' </audio>\n' +
  299. ' {footer}\n' +
  300. '</div>',
  301. tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  302. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  303. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  304. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  305. ' </object>\n' +
  306. ' {footer}\n' +
  307. '</div>\n',
  308. tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  309. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  310. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  311. ' <param name="movie" value="{caption}" />\n' +
  312. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  313. ' </object>\n' +
  314. ' {footer}\n' +
  315. '</div>',
  316. tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  317. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  318. ' ' + DEFAULT_PREVIEW + '\n' +
  319. ' {footer}\n' +
  320. '</div>',
  321. defaultLayoutTemplates = {
  322. main1: tMain1,
  323. main2: tMain2,
  324. preview: tPreview,
  325. icon: tIcon,
  326. caption: tCaption,
  327. modal: tModal,
  328. progress: tProgress,
  329. footer: tFooter,
  330. actions: tActions,
  331. actionDelete: tActionDelete,
  332. actionUpload: tActionUpload
  333. },
  334. defaultPreviewTemplates = {
  335. generic: tGeneric,
  336. html: tHtml,
  337. image: tImage,
  338. text: tText,
  339. video: tVideo,
  340. audio: tAudio,
  341. flash: tFlash,
  342. object: tObject,
  343. other: tOther
  344. },
  345. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
  346. defaultPreviewSettings = {
  347. image: {width: "auto", height: "160px"},
  348. html: {width: "213px", height: "160px"},
  349. text: {width: "160px", height: "160px"},
  350. video: {width: "213px", height: "160px"},
  351. audio: {width: "213px", height: "80px"},
  352. flash: {width: "213px", height: "160px"},
  353. object: {width: "160px", height: "160px"},
  354. other: {width: "160px", height: "160px"}
  355. },
  356. defaultFileTypeSettings = {
  357. image: function (vType, vName) {
  358. return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  359. },
  360. html: function (vType, vName) {
  361. return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i);
  362. },
  363. text: function (vType, vName) {
  364. return (vType !== undefined && vType.match('text.*')) || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  365. },
  366. video: function (vType, vName) {
  367. return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm)$/i)) || vName.match(/\.(og?|mp4|webm)$/i);
  368. },
  369. audio: function (vType, vName) {
  370. return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  371. },
  372. flash: function (vType, vName) {
  373. return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  374. },
  375. object: function () {
  376. return true;
  377. },
  378. other: function () {
  379. return true;
  380. }
  381. },
  382. isEmpty = function (value, trim) {
  383. return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === '');
  384. },
  385. isArray = function (a) {
  386. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  387. },
  388. isSet = function (needle, haystack) {
  389. return (typeof haystack === 'object' && needle in haystack);
  390. },
  391. getElement = function (options, param, value) {
  392. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  393. },
  394. uniqId = function () {
  395. return Math.round(new Date().getTime() + (Math.random() * 100));
  396. },
  397. htmlEncode = function (str) {
  398. return String(str).repl('&', '&amp;')
  399. .repl('"', '&quot;')
  400. .repl("'", '&#39;')
  401. .repl('<', '&lt;')
  402. .repl('>', '&gt;');
  403. },
  404. replaceTags = function (str, tags) {
  405. var out = str;
  406. $.each(tags, function (key, value) {
  407. if (typeof value === "function") {
  408. value = value();
  409. }
  410. out = out.repl(key, value);
  411. });
  412. return out;
  413. },
  414. objUrl = window.URL || window.webkitURL,
  415. FileInput = function (element, options) {
  416. this.$element = $(element);
  417. if (hasFileAPISupport() || isIE(9)) {
  418. this.init(options);
  419. this.listen();
  420. } else {
  421. this.$element.removeClass('file-loading');
  422. }
  423. };
  424. FileInput.prototype = {
  425. constructor: FileInput,
  426. init: function (options) {
  427. var self = this, $el = self.$element, t;
  428. $.each(options, function (key, value) {
  429. if (key === 'maxFileCount' || key === 'maxFileSize') {
  430. self[key] = getNum(value);
  431. }
  432. self[key] = value;
  433. });
  434. self.fileInputCleared = false;
  435. self.fileBatchCompleted = true;
  436. if (isEmpty(self.allowedPreviewTypes)) {
  437. self.allowedPreviewTypes = defaultPreviewTypes;
  438. }
  439. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  440. self.reader = null;
  441. self.formdata = {};
  442. self.isIE9 = isIE(9);
  443. self.isIE10 = isIE(10);
  444. self.filestack = [];
  445. self.ajaxRequests = [];
  446. self.isError = false;
  447. self.uploadAborted = false;
  448. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  449. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  450. self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl);
  451. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  452. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  453. self.captionTemplate = self.getLayoutTemplate('caption');
  454. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  455. if (isEmpty(self.$element.attr('id'))) {
  456. self.$element.attr('id', uniqId());
  457. }
  458. if (self.$container === undefined) {
  459. self.$container = self.createContainer();
  460. } else {
  461. self.refreshContainer();
  462. }
  463. self.$progress = self.$container.find('.kv-upload-progress');
  464. self.$btnUpload = self.$container.find('.kv-fileinput-upload');
  465. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  466. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  467. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  468. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  469. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  470. self.$errorContainer = getElement(options, 'elErrorContainer',
  471. self.$previewContainer.find('.kv-fileinput-error'));
  472. if (!isEmpty(self.msgErrorClass)) {
  473. addCss(self.$errorContainer, self.msgErrorClass);
  474. }
  475. self.$errorContainer.hide();
  476. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  477. self.previewInitId = "preview-" + uniqId();
  478. self.id = self.$element.attr('id');
  479. previewCache.init(self);
  480. self.initPreview(true);
  481. self.initPreviewDeletes();
  482. self.options = options;
  483. self.setFileDropZoneTitle();
  484. self.uploadCount = 0;
  485. self.uploadPercent = 0;
  486. self.$element.removeClass('file-loading');
  487. t = self.getLayoutTemplate('progress');
  488. self.progressTemplate = t.replace('{class}', self.progressClass);
  489. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  490. self.setEllipsis();
  491. },
  492. parseError: function (jqXHR, errorThrown, fileName) {
  493. var self = this, errMsg = $.trim(errorThrown + ''),
  494. dot = errMsg.slice(-1) === '.' ? '' : '.',
  495. text = $(jqXHR.responseText).text();
  496. if (self.showAjaxErrorDetails) {
  497. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  498. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  499. errMsg += dot + text;
  500. } else {
  501. errMsg += dot;
  502. }
  503. return fileName ? '<b>' + fileName + ': </b>' + jqXHR : errMsg;
  504. },
  505. raise: function (event, params) {
  506. var self = this, e = $.Event(event), out;
  507. if (params !== undefined) {
  508. self.$element.trigger(e, params);
  509. } else {
  510. self.$element.trigger(e);
  511. }
  512. out = e.result || false;
  513. if (!out) {
  514. return;
  515. }
  516. switch (event) {
  517. // ignore these events
  518. case 'filebatchuploadcomplete':
  519. case 'filebatchuploadsuccess':
  520. case 'fileuploaded':
  521. case 'fileclear':
  522. case 'filecleared':
  523. case 'filereset':
  524. case 'fileerror':
  525. case 'filefoldererror':
  526. case 'fileuploaderror':
  527. case 'filebatchuploaderror':
  528. case 'filedeleteerror':
  529. case 'filecustomerror':
  530. break;
  531. // can trigger filecustomerror to abort upload
  532. default:
  533. self.uploadAborted = out;
  534. break;
  535. }
  536. },
  537. getLayoutTemplate: function (t) {
  538. var self = this,
  539. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  540. if (isEmpty(self.customLayoutTags)) {
  541. return template;
  542. }
  543. return replaceTags(template, self.customLayoutTags);
  544. },
  545. getPreviewTemplate: function (t) {
  546. var self = this,
  547. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  548. template = template.repl('{previewFileIcon}', self.previewFileIcon);
  549. if (isEmpty(self.customPreviewTags)) {
  550. return template;
  551. }
  552. return replaceTags(template, self.customPreviewTags);
  553. },
  554. getOutData: function (jqXHR, responseData, filesData) {
  555. var self = this;
  556. jqXHR = jqXHR || {};
  557. responseData = responseData || {};
  558. filesData = filesData || self.filestack.slice(0) || {};
  559. return {
  560. form: self.formdata,
  561. files: filesData,
  562. extra: self.getExtraData(),
  563. response: responseData,
  564. reader: self.reader,
  565. jqXHR: jqXHR
  566. };
  567. },
  568. setEllipsis: function () {
  569. var self = this, $capCont = self.$captionContainer, $cap = self.$caption,
  570. $div = $cap.clone().css('height', 'auto').hide();
  571. $capCont.parent().before($div);
  572. $capCont.removeClass('kv-has-ellipsis');
  573. if ($div.outerWidth() > $cap.outerWidth()) {
  574. $capCont.addClass('kv-has-ellipsis');
  575. }
  576. $div.remove();
  577. },
  578. listen: function () {
  579. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile,
  580. $form = $el.closest('form');
  581. $el.on('change', $.proxy(self.change, self));
  582. $(window).on('resize', function () {
  583. self.setEllipsis();
  584. });
  585. $btnFile.off('click').on('click', function () {
  586. self.raise('filebrowse');
  587. if (self.isError && !self.isUploadable) {
  588. self.clear();
  589. }
  590. $cap.focus();
  591. });
  592. $form.off('reset').on('reset', $.proxy(self.reset, self));
  593. self.$container.off('click')
  594. .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self))
  595. .on('click', '.fileinput-cancel', $.proxy(self.cancel, self));
  596. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  597. self.initDragDrop();
  598. }
  599. if (!self.isUploadable) {
  600. $form.on('submit', $.proxy(self.submitForm, self));
  601. }
  602. self.$container.find('.kv-fileinput-upload').off('click').on('click', function (e) {
  603. if (!self.isUploadable) {
  604. return;
  605. }
  606. e.preventDefault();
  607. if (!$(this).hasClass('disabled') && isEmpty($(this).attr('disabled'))) {
  608. self.upload();
  609. }
  610. });
  611. },
  612. submitForm: function () {
  613. var self = this, $el = self.$element, files = $el.get(0).files;
  614. if (files && files.length < self.minFileCount && self.minFileCount > 0) {
  615. self.noFilesError({});
  616. return false;
  617. }
  618. return !self.abort({});
  619. },
  620. abort: function (params) {
  621. var self = this, data;
  622. if (self.uploadAborted && typeof self.uploadAborted === "object" && self.uploadAborted.message !== undefined) {
  623. if (self.uploadAborted.data !== undefined) {
  624. data = self.getOutData({}, self.uploadAborted.data);
  625. } else {
  626. data = self.getOutData();
  627. }
  628. data = $.extend(data, params);
  629. self.showUploadError(self.uploadAborted.message, data, 'filecustomerror');
  630. return true;
  631. }
  632. return false;
  633. },
  634. noFilesError: function (params) {
  635. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  636. msg = self.msgFilesTooLess.repl('{n}', self.minFileCount).repl('{files}', label),
  637. $error = self.$errorContainer;
  638. $error.html(msg);
  639. self.isError = true;
  640. self.updateFileDetails(0);
  641. $error.fadeIn(800);
  642. self.raise('fileerror', [params]);
  643. self.clearFileInput();
  644. addCss(self.$container, 'has-error');
  645. },
  646. setProgress: function (p) {
  647. var self = this, pct = Math.min(p, 100),
  648. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  649. self.$progress.html(template.repl('{percent}', pct));
  650. },
  651. upload: function () {
  652. var self = this, totLen = self.getFileStack().length, params = {},
  653. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  654. if (totLen < self.minFileCount && self.minFileCount > 0) {
  655. self.noFilesError(params);
  656. return;
  657. }
  658. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  659. return;
  660. }
  661. self.resetUpload();
  662. self.$progress.removeClass('hide');
  663. self.uploadCount = 0;
  664. self.uploadPercent = 0;
  665. self.lock();
  666. self.setProgress(0);
  667. if (totLen === 0 && hasExtraData) {
  668. self.uploadExtraOnly();
  669. return;
  670. }
  671. len = self.filestack.length;
  672. self.hasInitData = false;
  673. if (self.uploadAsync && self.showPreview) {
  674. outData = self.getOutData();
  675. self.raise('filebatchpreupload', [outData]);
  676. self.fileBatchCompleted = false;
  677. self.uploadCache = {content: [], config: [], append: true};
  678. for (i = 0; i < len; i += 1) {
  679. if (self.filestack[i] !== undefined) {
  680. self.uploadSingle(i, self.filestack, true);
  681. }
  682. }
  683. return;
  684. }
  685. self.uploadBatch();
  686. },
  687. lock: function () {
  688. var self = this;
  689. self.resetErrors();
  690. self.disable();
  691. if (self.showRemove) {
  692. addCss(self.$container.find('.fileinput-remove'), 'hide');
  693. }
  694. if (self.showCancel) {
  695. self.$container.find('.fileinput-cancel').removeClass('hide');
  696. }
  697. self.raise('filelock', [self.filestack, self.getExtraData()]);
  698. },
  699. unlock: function (reset) {
  700. var self = this;
  701. if (reset === undefined) {
  702. reset = true;
  703. }
  704. self.enable();
  705. if (self.showCancel) {
  706. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  707. }
  708. if (self.showRemove) {
  709. self.$container.find('.fileinput-remove').removeClass('hide');
  710. }
  711. if (reset) {
  712. self.resetFileStack();
  713. }
  714. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  715. },
  716. resetFileStack: function () {
  717. var self = this, i = 0, newstack = [];
  718. self.$preview.find(PREVIEW_FRAMES).each(function () {
  719. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  720. file = self.filestack[ind];
  721. if (ind === -1) {
  722. return;
  723. }
  724. if (file !== undefined) {
  725. newstack[i] = file;
  726. $thumb.attr({
  727. 'id': self.previewInitId + '-' + i,
  728. 'data-fileindex': i
  729. });
  730. i += 1;
  731. } else {
  732. $thumb.attr({
  733. 'id': 'uploaded-' + uniqId(),
  734. 'data-fileindex': '-1'
  735. });
  736. }
  737. });
  738. self.filestack = newstack;
  739. },
  740. refresh: function (options) {
  741. var self = this, $el = self.$element, $zone,
  742. params = (arguments.length) ? $.extend(self.options, options) : self.options;
  743. $el.off();
  744. self.init(params);
  745. $zone = self.$container.find('.file-drop-zone');
  746. $zone.off('dragenter dragover drop');
  747. $(document).off('dragenter dragover drop');
  748. self.listen();
  749. self.setFileDropZoneTitle();
  750. },
  751. initDragDrop: function () {
  752. var self = this, $zone = self.$container.find('.file-drop-zone');
  753. $zone.off('dragenter dragover drop');
  754. $(document).off('dragenter dragover drop');
  755. $zone.on('dragenter dragover', function (e) {
  756. e.stopPropagation();
  757. e.preventDefault();
  758. if (self.isDisabled) {
  759. return;
  760. }
  761. addCss($(this), 'highlighted');
  762. });
  763. $zone.on('dragleave', function (e) {
  764. e.stopPropagation();
  765. e.preventDefault();
  766. if (self.isDisabled) {
  767. return;
  768. }
  769. $(this).removeClass('highlighted');
  770. });
  771. $zone.on('drop', function (e) {
  772. e.preventDefault();
  773. if (self.isDisabled) {
  774. return;
  775. }
  776. self.change(e, 'dragdrop');
  777. $(this).removeClass('highlighted');
  778. });
  779. $(document).on('dragenter dragover drop', function (e) {
  780. e.stopPropagation();
  781. e.preventDefault();
  782. });
  783. },
  784. setFileDropZoneTitle: function () {
  785. var self = this, $zone = self.$container.find('.file-drop-zone');
  786. $zone.find('.' + self.dropZoneTitleClass).remove();
  787. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  788. return;
  789. }
  790. if ($zone.find('.file-preview-frame').length === 0) {
  791. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  792. }
  793. self.$container.removeClass('file-input-new');
  794. addCss(self.$container, 'file-input-ajax-new');
  795. },
  796. initFileActions: function () {
  797. var self = this;
  798. self.$preview.find('.kv-file-remove').each(function () {
  799. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  800. ind = $frame.attr('data-fileindex'), n, cap;
  801. $el.off('click').on('click', function () {
  802. $frame.fadeOut('slow', function () {
  803. self.filestack[ind] = undefined;
  804. self.clearObjects($frame);
  805. $frame.remove();
  806. var filestack = self.getFileStack(), len = filestack.length,
  807. chk = previewCache.count(self.id);
  808. self.clearFileInput();
  809. if (len === 0 && chk === 0) {
  810. self.reset();
  811. } else {
  812. n = chk + len;
  813. cap = n > 1 ? self.msgSelected.repl('{n}', n) : filestack[0].name;
  814. self.setCaption(cap);
  815. }
  816. });
  817. });
  818. });
  819. self.$preview.find('.kv-file-upload').each(function () {
  820. var $el = $(this);
  821. $el.off('click').on('click', function () {
  822. var $frame = $el.closest('.file-preview-frame'),
  823. ind = $frame.attr('data-fileindex');
  824. self.uploadSingle(ind, self.filestack, false);
  825. });
  826. });
  827. },
  828. renderFileFooter: function (caption, width) {
  829. var self = this, config = self.fileActionSettings, footer,
  830. template = self.getLayoutTemplate('footer');
  831. if (self.isUploadable) {
  832. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false, false));
  833. return footer.repl('{caption}', caption)
  834. .repl('{width}', width)
  835. .repl('{indicator}', config.indicatorNew)
  836. .repl('{indicatorTitle}', config.indicatorNewTitle);
  837. }
  838. return template.repl('{actions}', '')
  839. .repl('{caption}', caption)
  840. .repl('{width}', width)
  841. .repl('{indicator}', '')
  842. .repl('{indicatorTitle}', '');
  843. },
  844. renderFileActions: function (showUpload, showDelete, disabled, url, key, index) {
  845. if (!showUpload && !showDelete) {
  846. return '';
  847. }
  848. var self = this,
  849. vUrl = url === false ? '' : ' data-url="' + url + '"',
  850. vKey = key === false ? '' : ' data-key="' + key + '"',
  851. btnDelete = self.getLayoutTemplate('actionDelete'),
  852. btnUpload = '',
  853. template = self.getLayoutTemplate('actions'),
  854. otherButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  855. config = self.fileActionSettings,
  856. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  857. btnDelete = btnDelete
  858. .repl('{removeClass}', removeClass)
  859. .repl('{removeIcon}', config.removeIcon)
  860. .repl('{removeTitle}', config.removeTitle)
  861. .repl('{dataUrl}', vUrl)
  862. .repl('{dataKey}', vKey);
  863. if (showUpload) {
  864. btnUpload = self.getLayoutTemplate('actionUpload')
  865. .repl('{uploadClass}', config.uploadClass)
  866. .repl('{uploadIcon}', config.uploadIcon)
  867. .repl('{uploadTitle}', config.uploadTitle);
  868. }
  869. return template
  870. .repl('{delete}', btnDelete)
  871. .repl('{upload}', btnUpload)
  872. .repl('{other}', otherButtons);
  873. },
  874. initPreview: function (isInit) {
  875. var self = this, cap, out;
  876. if (!previewCache.count(self.id)) {
  877. self.$preview.html('');
  878. self.setCaption('');
  879. return;
  880. }
  881. out = previewCache.out(self.id);
  882. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  883. self.$preview.html(out.content);
  884. self.setCaption(cap);
  885. if (!isEmpty(out.content)) {
  886. self.$container.removeClass('file-input-new');
  887. }
  888. },
  889. initPreviewDeletes: function () {
  890. var self = this, deleteExtraData = self.deleteExtraData || {},
  891. resetProgress = function () {
  892. if (self.$preview.find('.kv-file-remove').length === 0) {
  893. self.reset();
  894. }
  895. };
  896. self.$preview.find('.kv-file-remove').each(function () {
  897. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  898. cache = previewCache.data[self.id], index, config, extraData,
  899. vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), settings,
  900. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  901. if (typeof extraData === "function") {
  902. extraData = extraData();
  903. }
  904. if (vUrl === undefined || vKey === undefined) {
  905. return;
  906. }
  907. settings = $.extend({
  908. url: vUrl,
  909. type: 'DELETE',
  910. dataType: 'json',
  911. data: $.extend({key: vKey}, extraData),
  912. beforeSend: function (jqXHR) {
  913. addCss($frame, 'file-uploading');
  914. addCss($el, 'disabled');
  915. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  916. },
  917. success: function (data, textStatus, jqXHR) {
  918. index = parseInt($frame.data('fileindex').replace('init_', ''));
  919. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  920. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  921. if (data === undefined || data.error === undefined) {
  922. previewCache.unset(self.id, index);
  923. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  924. } else {
  925. params.jqXHR = jqXHR;
  926. params.response = data;
  927. self.showError(data.error, params, 'filedeleteerror');
  928. $frame.removeClass('file-uploading');
  929. $el.removeClass('disabled');
  930. resetProgress();
  931. return;
  932. }
  933. $frame.removeClass('file-uploading').addClass('file-deleted');
  934. $frame.fadeOut('slow', function () {
  935. self.clearObjects($frame);
  936. $frame.remove();
  937. resetProgress();
  938. if (!previewCache.count(self.id)) {
  939. self.reset();
  940. }
  941. });
  942. },
  943. error: function (jqXHR, textStatus, errorThrown) {
  944. var errMsg = self.parseError(jqXHR, errorThrown);
  945. params.jqXHR = jqXHR;
  946. params.response = {};
  947. self.showError(errMsg, params, 'filedeleteerror');
  948. $frame.removeClass('file-uploading');
  949. resetProgress();
  950. }
  951. }, self.ajaxDeleteSettings);
  952. $el.off('click').on('click', function () {
  953. $.ajax(settings);
  954. });
  955. });
  956. },
  957. clearObjects: function ($el) {
  958. $el.find('video audio').each(function () {
  959. this.pause();
  960. $(this).remove();
  961. });
  962. $el.find('img object div').each(function () {
  963. $(this).remove();
  964. });
  965. },
  966. clearFileInput: function () {
  967. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  968. if (isEmpty($el.val())) {
  969. return;
  970. }
  971. // Fix for IE ver < 11, that does not clear file inputs
  972. // Requires a sequence of steps to prevent IE crashing but
  973. // still allow clearing of the file input.
  974. if (self.isIE9 || self.isIE10) {
  975. $srcFrm = $el.closest('form');
  976. $tmpFrm = $(document.createElement('form'));
  977. $tmpEl = $(document.createElement('div'));
  978. $el.before($tmpEl);
  979. if ($srcFrm.length) {
  980. $srcFrm.after($tmpFrm);
  981. } else {
  982. $tmpEl.after($tmpFrm);
  983. }
  984. $tmpFrm.append($el).trigger('reset');
  985. $tmpEl.before($el).remove();
  986. $tmpFrm.remove();
  987. } else { // normal input clear behavior for other sane browsers
  988. $el.val('');
  989. }
  990. self.fileInputCleared = true;
  991. },
  992. resetUpload: function () {
  993. var self = this;
  994. self.uploadCache = {content: [], config: [], append: true};
  995. self.uploadCount = 0;
  996. self.uploadPercent = 0;
  997. self.$btnUpload.removeAttr('disabled');
  998. self.setProgress(0);
  999. addCss(self.$progress, 'hide');
  1000. self.resetErrors(false);
  1001. self.uploadAborted = false;
  1002. self.ajaxRequests = [];
  1003. },
  1004. cancel: function () {
  1005. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1006. if (len > 0) {
  1007. for (i = 0; i < len; i += 1) {
  1008. xhr[i].abort();
  1009. }
  1010. }
  1011. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1012. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1013. $thumb.removeClass('file-uploading');
  1014. if (self.filestack[ind] !== undefined) {
  1015. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1016. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1017. }
  1018. self.unlock();
  1019. });
  1020. },
  1021. clear: function () {
  1022. var self = this, cap;
  1023. if (!self.isIE9 && self.reader instanceof FileReader) {
  1024. self.reader.abort();
  1025. }
  1026. self.$btnUpload.removeAttr('disabled');
  1027. self.resetUpload();
  1028. self.filestack = [];
  1029. self.clearFileInput();
  1030. self.resetErrors(true);
  1031. self.raise('fileclear');
  1032. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1033. self.showFileIcon();
  1034. self.resetPreview();
  1035. self.setEllipsis();
  1036. self.initPreviewDeletes();
  1037. self.$container.removeClass('file-input-new');
  1038. } else {
  1039. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1040. self.clearObjects($(this));
  1041. });
  1042. self.$preview.html('');
  1043. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1044. self.$caption.html(cap);
  1045. self.setEllipsis();
  1046. self.$caption.attr('title', '');
  1047. addCss(self.$container, 'file-input-new');
  1048. }
  1049. if (self.$container.find('.file-preview-frame').length === 0) {
  1050. self.initialCaption = '';
  1051. self.$caption.html('');
  1052. self.setEllipsis();
  1053. self.$captionContainer.find('.kv-caption-icon').hide();
  1054. }
  1055. self.hideFileIcon();
  1056. self.raise('filecleared');
  1057. self.$captionContainer.focus();
  1058. self.setFileDropZoneTitle();
  1059. },
  1060. resetPreview: function () {
  1061. var self = this, out;
  1062. if (previewCache.count(self.id)) {
  1063. out = previewCache.out(self.id);
  1064. self.$preview.html(out.content);
  1065. self.setCaption(out.caption);
  1066. } else {
  1067. self.$preview.html('');
  1068. self.$caption.html('');
  1069. }
  1070. },
  1071. reset: function () {
  1072. var self = this;
  1073. self.clear();
  1074. self.resetPreview();
  1075. self.setEllipsis();
  1076. self.$container.find('.fileinput-filename').text('');
  1077. self.raise('filereset');
  1078. if (self.initialPreview.length > 0) {
  1079. self.$container.removeClass('file-input-new');
  1080. }
  1081. self.setFileDropZoneTitle();
  1082. if (self.isUploadable) {
  1083. self.resetUpload();
  1084. }
  1085. self.filestack = [];
  1086. self.formdata = {};
  1087. },
  1088. disable: function () {
  1089. var self = this;
  1090. self.isDisabled = true;
  1091. self.raise('filedisabled');
  1092. self.$element.attr('disabled', 'disabled');
  1093. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1094. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  1095. self.initDragDrop();
  1096. },
  1097. enable: function () {
  1098. var self = this;
  1099. self.isDisabled = false;
  1100. self.raise('fileenabled');
  1101. self.$element.removeAttr('disabled');
  1102. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1103. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  1104. self.initDragDrop();
  1105. },
  1106. getExtraData: function () {
  1107. var self = this, data = self.uploadExtraData;
  1108. if (typeof self.uploadExtraData === "function") {
  1109. data = self.uploadExtraData();
  1110. }
  1111. return data;
  1112. },
  1113. uploadExtra: function () {
  1114. var self = this, data = self.getExtraData();
  1115. if (data.length === 0) {
  1116. return;
  1117. }
  1118. $.each(data, function (key, value) {
  1119. self.formdata.append(key, value);
  1120. });
  1121. },
  1122. initXhr: function (xhrobj, factor) {
  1123. var self = this;
  1124. if (xhrobj.upload) {
  1125. xhrobj.upload.addEventListener('progress', function (event) {
  1126. var pct = 0, position = event.loaded || event.position, total = event.total;
  1127. if (event.lengthComputable) {
  1128. pct = Math.ceil(position / total * factor);
  1129. }
  1130. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1131. self.setProgress(self.uploadPercent);
  1132. }, false);
  1133. }
  1134. return xhrobj;
  1135. },
  1136. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  1137. var self = this, settings;
  1138. self.uploadExtra();
  1139. settings = $.extend({
  1140. xhr: function () {
  1141. var xhrobj = $.ajaxSettings.xhr();
  1142. return self.initXhr(xhrobj, 98);
  1143. },
  1144. url: self.uploadUrl,
  1145. type: 'POST',
  1146. dataType: 'json',
  1147. data: self.formdata,
  1148. cache: false,
  1149. processData: false,
  1150. contentType: false,
  1151. beforeSend: fnBefore,
  1152. success: fnSuccess,
  1153. complete: fnComplete,
  1154. error: fnError
  1155. }, self.ajaxSettings);
  1156. self.ajaxRequests.push($.ajax(settings));
  1157. },
  1158. initUploadSuccess: function (out, $thumb, allFiles) {
  1159. var self = this, append, data, index, $newThumb, content, config;
  1160. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1161. return;
  1162. }
  1163. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1164. self.hasInitData = true;
  1165. content = out.initialPreview || [];
  1166. config = out.initialPreviewConfig || [];
  1167. append = out.append === undefined || out.append ? true : false;
  1168. self.overwriteInitial = false;
  1169. if ($thumb !== undefined && !!allFiles) {
  1170. index = previewCache.add(self.id, content, config[0], append);
  1171. data = previewCache.get(self.id, index, false);
  1172. $newThumb = $(data).hide();
  1173. $thumb.after($newThumb).fadeOut('slow', function () {
  1174. $newThumb.fadeIn('slow').css('display:inline-block');
  1175. self.initPreviewDeletes();
  1176. });
  1177. } else {
  1178. if (allFiles) {
  1179. self.uploadCache.content.push(content[0]);
  1180. self.uploadCache.config.push(config[0]);
  1181. self.uploadCache.append = append;
  1182. } else {
  1183. previewCache.set(self.id, content, config, append);
  1184. self.initPreview();
  1185. self.initPreviewDeletes();
  1186. }
  1187. }
  1188. }
  1189. },
  1190. uploadSingle: function (i, files, allFiles) {
  1191. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1192. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1193. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1194. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  1195. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1196. setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError,
  1197. params = {id: previewId, index: i};
  1198. self.formdata = formdata;
  1199. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1200. return;
  1201. }
  1202. chkComplete = function () {
  1203. var $thumbs = self.$preview.find(PREVIEW_FRAMES + '.file-uploading');
  1204. if ($thumbs.length > 0 && self.fileBatchCompleted) {
  1205. return;
  1206. }
  1207. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.append);
  1208. if (self.hasInitData) {
  1209. self.initPreview();
  1210. self.initPreviewDeletes();
  1211. }
  1212. self.setProgress(100);
  1213. self.unlock();
  1214. self.clearFileInput();
  1215. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1216. self.fileBatchCompleted = true;
  1217. };
  1218. setIndicator = function (icon, msg) {
  1219. $indicator.html(config[icon]);
  1220. $indicator.attr('title', config[msg]);
  1221. };
  1222. updateProgress = function () {
  1223. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1224. return;
  1225. }
  1226. self.uploadCount += 1;
  1227. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1228. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1229. self.setProgress(self.uploadPercent);
  1230. self.initPreviewDeletes();
  1231. };
  1232. resetActions = function () {
  1233. $btnUpload.removeAttr('disabled');
  1234. $btnDelete.removeAttr('disabled');
  1235. $thumb.removeClass('file-uploading');
  1236. };
  1237. fnBefore = function (jqXHR) {
  1238. outData = self.getOutData(jqXHR);
  1239. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  1240. addCss($thumb, 'file-uploading');
  1241. $btnUpload.attr('disabled', true);
  1242. $btnDelete.attr('disabled', true);
  1243. if (!allFiles) {
  1244. self.lock();
  1245. }
  1246. self.raise('filepreupload', [outData, previewId, i]);
  1247. params = $.extend(params, outData);
  1248. if (self.abort(params)) {
  1249. jqXHR.abort();
  1250. self.setProgress(100);
  1251. }
  1252. };
  1253. fnSuccess = function (data, textStatus, jqXHR) {
  1254. outData = self.getOutData(jqXHR, data);
  1255. params = $.extend(params, outData);
  1256. setTimeout(function () {
  1257. if (data.error === undefined) {
  1258. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  1259. $btnUpload.hide();
  1260. $btnDelete.hide();
  1261. self.filestack[i] = undefined;
  1262. self.raise('fileuploaded', [outData, previewId, i]);
  1263. self.initUploadSuccess(data, $thumb, allFiles);
  1264. if (!allFiles) {
  1265. self.resetFileStack();
  1266. }
  1267. } else {
  1268. setIndicator('indicatorError', 'indicatorErrorTitle');
  1269. self.showUploadError(data.error, params);
  1270. }
  1271. }, 100);
  1272. };
  1273. fnComplete = function () {
  1274. setTimeout(function () {
  1275. updateProgress();
  1276. resetActions();
  1277. if (!allFiles) {
  1278. self.unlock(false);
  1279. } else {
  1280. setTimeout(function () {
  1281. chkComplete();
  1282. }, 500);
  1283. }
  1284. }, 100);
  1285. };
  1286. fnError = function (jqXHR, textStatus, errorThrown) {
  1287. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1288. setIndicator('indicatorError', 'indicatorErrorTitle');
  1289. params = $.extend(params, self.getOutData(jqXHR));
  1290. self.showUploadError(errMsg, params);
  1291. };
  1292. formdata.append(self.uploadFileAttr, files[i]);
  1293. formdata.append('file_id', i);
  1294. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1295. },
  1296. uploadBatch: function () {
  1297. var self = this, files = self.filestack, total = files.length, config,
  1298. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1299. setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1300. params = {};
  1301. self.formdata = new FormData();
  1302. if (total === 0 || !hasPostData || self.abort(params)) {
  1303. return;
  1304. }
  1305. config = self.fileActionSettings;
  1306. setIndicator = function (i, icon, msg) {
  1307. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1308. $indicator.html(config[icon]);
  1309. $indicator.attr('title', config[msg]);
  1310. };
  1311. enableActions = function (i) {
  1312. var $thumb = $('#' + self.previewInitId + "-" + i + ':not(.file-preview-initial)'),
  1313. $btnUpload = $thumb.find('.kv-file-upload'),
  1314. $btnDelete = $thumb.find('.kv-file-delete');
  1315. $thumb.removeClass('file-uploading');
  1316. $btnUpload.removeAttr('disabled');
  1317. $btnDelete.removeAttr('disabled');
  1318. };
  1319. setAllUploaded = function () {
  1320. $.each(files, function (key, data) {
  1321. self.filestack[key] = undefined;
  1322. });
  1323. self.clearFileInput();
  1324. };
  1325. fnBefore = function (jqXHR) {
  1326. self.lock();
  1327. var outData = self.getOutData(jqXHR);
  1328. if (self.showPreview) {
  1329. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1330. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1331. addCss($thumb, 'file-uploading');
  1332. $btnUpload.attr('disabled', true);
  1333. $btnDelete.attr('disabled', true);
  1334. });
  1335. }
  1336. self.raise('filebatchpreupload', [outData]);
  1337. if (self.abort(outData)) {
  1338. jqXHR.abort();
  1339. }
  1340. };
  1341. fnSuccess = function (data, textStatus, jqXHR) {
  1342. var outData = self.getOutData(jqXHR, data),
  1343. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1344. if (data.error === undefined || isEmpty(data.error)) {
  1345. self.raise('filebatchuploadsuccess', [outData]);
  1346. setAllUploaded();
  1347. if (self.showPreview) {
  1348. self.$preview.find('.kv-file-upload').hide();
  1349. self.$preview.find('.kv-file-remove').hide();
  1350. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1351. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1352. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1353. enableActions(key);
  1354. });
  1355. self.initUploadSuccess(data);
  1356. } else {
  1357. self.reset();
  1358. }
  1359. } else {
  1360. if (self.showPreview) {
  1361. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1362. var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10);
  1363. enableActions(key);
  1364. if (keys.length === 0) {
  1365. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1366. return;
  1367. }
  1368. if ($.inArray(key, keys) !== -1) {
  1369. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1370. } else {
  1371. $thumb.find('.kv-file-upload').hide();
  1372. $thumb.find('.kv-file-remove').hide();
  1373. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1374. self.filestack[key] = undefined;
  1375. }
  1376. });
  1377. self.initUploadSuccess(data);
  1378. }
  1379. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1380. }
  1381. };
  1382. fnComplete = function () {
  1383. self.setProgress(100);
  1384. self.unlock();
  1385. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1386. self.clearFileInput();
  1387. };
  1388. fnError = function (jqXHR, textStatus, errorThrown) {
  1389. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1390. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1391. self.uploadFileCount = total - 1;
  1392. if (!self.showPreview) {
  1393. return;
  1394. }
  1395. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1396. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1397. $thumb.removeClass('file-uploading');
  1398. if (self.filestack[key] !== undefined) {
  1399. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1400. }
  1401. });
  1402. self.$preview.find(PREVIEW_FRAMES).removeClass('file-uploading');
  1403. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-upload').removeAttr('disabled');
  1404. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-delete').removeAttr('disabled');
  1405. };
  1406. $.each(files, function (key, data) {
  1407. if (!isEmpty(files[key])) {
  1408. self.formdata.append(self.uploadFileAttr, data);
  1409. }
  1410. });
  1411. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1412. },
  1413. uploadExtraOnly: function () {
  1414. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1415. self.formdata = new FormData();
  1416. if (self.abort(params)) {
  1417. return;
  1418. }
  1419. fnBefore = function (jqXHR) {
  1420. self.lock();
  1421. var outData = self.getOutData(jqXHR);
  1422. self.raise('filebatchpreupload', [outData]);
  1423. self.setProgress(50);
  1424. params.data = outData;
  1425. params.xhr = jqXHR;
  1426. if (self.abort(params)) {
  1427. jqXHR.abort();
  1428. self.setProgress(100);
  1429. }
  1430. };
  1431. fnSuccess = function (data, textStatus, jqXHR) {
  1432. var outData = self.getOutData(jqXHR, data);
  1433. if (data.error === undefined || isEmpty(data.error)) {
  1434. self.raise('filebatchuploadsuccess', [outData]);
  1435. self.clearFileInput();
  1436. self.initUploadSuccess(data);
  1437. } else {
  1438. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1439. }
  1440. };
  1441. fnComplete = function () {
  1442. self.setProgress(100);
  1443. self.unlock();
  1444. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1445. self.clearFileInput();
  1446. };
  1447. fnError = function (jqXHR, textStatus, errorThrown) {
  1448. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1449. params.data = outData;
  1450. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1451. };
  1452. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1453. },
  1454. hideFileIcon: function () {
  1455. if (this.overwriteInitial) {
  1456. this.$captionContainer.find('.kv-caption-icon').hide();
  1457. }
  1458. },
  1459. showFileIcon: function () {
  1460. this.$captionContainer.find('.kv-caption-icon').show();
  1461. },
  1462. resetErrors: function (fade) {
  1463. var self = this, $error = self.$errorContainer;
  1464. self.isError = false;
  1465. self.$container.removeClass('has-error');
  1466. $error.html('');
  1467. if (fade) {
  1468. $error.fadeOut('slow');
  1469. } else {
  1470. $error.hide();
  1471. }
  1472. },
  1473. showFolderError: function (folders) {
  1474. var self = this, $error = self.$errorContainer;
  1475. if (!folders) {
  1476. return;
  1477. }
  1478. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1479. $error.fadeIn(800);
  1480. addCss(self.$container, 'has-error');
  1481. self.raise('filefoldererror', [folders]);
  1482. },
  1483. showUploadError: function (msg, params, event) {
  1484. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1485. if ($error.find('ul').length === 0) {
  1486. $error.html('<ul><li>' + msg + '</li></ul>');
  1487. } else {
  1488. $error.find('ul').append('<li>' + msg + '</li>');
  1489. }
  1490. $error.fadeIn(800);
  1491. self.raise(ev, [params]);
  1492. addCss(self.$container, 'has-error');
  1493. return true;
  1494. },
  1495. showError: function (msg, params, event) {
  1496. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1497. params = params || {};
  1498. params.reader = self.reader;
  1499. $error.html(msg);
  1500. $error.fadeIn(800);
  1501. self.raise(ev, [params]);
  1502. if (!self.isUploadable) {
  1503. self.clearFileInput();
  1504. }
  1505. addCss(self.$container, 'has-error');
  1506. self.$btnUpload.attr('disabled', true);
  1507. return true;
  1508. },
  1509. errorHandler: function (evt, caption) {
  1510. var self = this, err = evt.target.error;
  1511. switch (err.code) {
  1512. case err.NOT_FOUND_ERR:
  1513. self.showError(self.msgFileNotFound.repl('{name}', caption));
  1514. break;
  1515. case err.SECURITY_ERR:
  1516. self.showError(self.msgFileSecured.repl('{name}', caption));
  1517. break;
  1518. case err.NOT_READABLE_ERR:
  1519. self.showError(self.msgFileNotReadable.repl('{name}', caption));
  1520. break;
  1521. case err.ABORT_ERR:
  1522. self.showError(self.msgFilePreviewAborted.repl('{name}', caption));
  1523. break;
  1524. default:
  1525. self.showError(self.msgFilePreviewError.repl('{name}', caption));
  1526. }
  1527. },
  1528. parseFileType: function (file) {
  1529. var self = this, isValid, vType, cat, i;
  1530. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1531. cat = defaultPreviewTypes[i];
  1532. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1533. vType = isValid(file.type, file.name) ? cat : '';
  1534. if (!isEmpty(vType)) {
  1535. return vType;
  1536. }
  1537. }
  1538. return 'other';
  1539. },
  1540. previewDefault: function (file, previewId, isDisabled) {
  1541. if (!this.showPreview) {
  1542. return;
  1543. }
  1544. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1545. config = self.previewSettings.other,
  1546. footer = self.renderFileFooter(file.name, config.width),
  1547. previewOtherTemplate = self.getPreviewTemplate('other'),
  1548. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1549. frameClass = '';
  1550. if (isDisabled === true) {
  1551. frameClass = ' btn disabled';
  1552. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1553. }
  1554. self.$preview.append("\n" + previewOtherTemplate
  1555. .repl('{previewId}', previewId)
  1556. .repl('{frameClass}', frameClass)
  1557. .repl('{fileindex}', ind)
  1558. .repl('{caption}', self.slug(file.name))
  1559. .repl('{width}', config.width)
  1560. .repl('{height}', config.height)
  1561. .repl('{type}', file.type)
  1562. .repl('{data}', data)
  1563. .repl('{footer}', footer));
  1564. $obj.on('load', function () {
  1565. objUrl.revokeObjectURL($obj.attr('data'));
  1566. });
  1567. },
  1568. previewFile: function (file, theFile, previewId, data) {
  1569. if (!this.showPreview) {
  1570. return;
  1571. }
  1572. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1573. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1574. tmplt = self.getPreviewTemplate(cat),
  1575. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1576. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1577. chkTypes = types.indexOf(cat) >= 0, id, height,
  1578. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1579. footer = self.renderFileFooter(caption, config.width), modal = '',
  1580. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1581. if (chkTypes && chkMimes) {
  1582. if (cat === 'text') {
  1583. strText = htmlEncode(theFile.target.result);
  1584. objUrl.revokeObjectURL(data);
  1585. if (strText.length > wrapLen) {
  1586. id = 'text-' + uniqId();
  1587. height = window.innerHeight * 0.75;
  1588. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1589. .repl('{title}', caption)
  1590. .repl('{height}', height)
  1591. .repl('{body}', strText);
  1592. wrapInd = wrapInd
  1593. .repl('{title}', caption)
  1594. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1595. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1596. }
  1597. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1598. .repl('{frameClass}', '')
  1599. .repl('{type}', file.type).repl('{width}', config.width)
  1600. .repl('{height}', config.height).repl('{data}', strText)
  1601. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1602. } else {
  1603. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1604. .repl('{frameClass}', '')
  1605. .repl('{type}', file.type).repl('{data}', data)
  1606. .repl('{width}', config.width).repl('{height}', config.height)
  1607. .repl('{footer}', footer).repl('{fileindex}', ind);
  1608. }
  1609. self.$preview.append("\n" + content);
  1610. self.autoSizeImage(previewId);
  1611. } else {
  1612. self.previewDefault(file, previewId);
  1613. }
  1614. },
  1615. slugDefault: function (text) {
  1616. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\-.\\\/ ]+/g, '');
  1617. },
  1618. getFileStack: function () {
  1619. var self = this;
  1620. return self.filestack.filter(function (n) {
  1621. return n !== undefined;
  1622. });
  1623. },
  1624. readFiles: function (files) {
  1625. this.reader = new FileReader();
  1626. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1627. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1628. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1629. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1630. throwError = function (msg, file, previewId, index) {
  1631. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1632. p2 = {id: previewId, index: index, file: file, files: files};
  1633. self.previewDefault(file, previewId, true);
  1634. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1635. };
  1636. function readFile(i) {
  1637. if (isEmpty($el.attr('multiple'))) {
  1638. numFiles = 1;
  1639. }
  1640. if (i >= numFiles) {
  1641. $container.removeClass('loading');
  1642. $status.html('');
  1643. return;
  1644. }
  1645. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1646. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1647. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1648. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1649. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1650. if (!isEmpty(fileExt)) {
  1651. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1652. }
  1653. fileSize = fileSize.toFixed(2);
  1654. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1655. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1656. .repl('{size}', fileSize)
  1657. .repl('{maxSize}', self.maxFileSize);
  1658. self.isError = throwError(msg, file, previewId, i);
  1659. return;
  1660. }
  1661. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1662. for (j = 0; j < fileTypes.length; j += 1) {
  1663. typ = fileTypes[j];
  1664. checkFile = settings[typ];
  1665. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1666. fileCount += isEmpty(chk) ? 0 : chk.length;
  1667. }
  1668. if (fileCount === 0) {
  1669. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1670. self.isError = throwError(msg, file, previewId, i);
  1671. return;
  1672. }
  1673. }
  1674. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1675. chk = caption.match(fileExtExpr);
  1676. fileCount += isEmpty(chk) ? 0 : chk.length;
  1677. if (fileCount === 0) {
  1678. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1679. strExt);
  1680. self.isError = throwError(msg, file, previewId, i);
  1681. return;
  1682. }
  1683. }
  1684. if (!self.showPreview) {
  1685. self.filestack.push(file);
  1686. setTimeout(readFile(i + 1), 100);
  1687. self.raise('fileloaded', [file, previewId, i, reader]);
  1688. return;
  1689. }
  1690. if ($preview.length > 0 && FileReader !== undefined) {
  1691. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1692. $container.addClass('loading');
  1693. reader.onerror = function (evt) {
  1694. self.errorHandler(evt, caption);
  1695. };
  1696. reader.onload = function (theFile) {
  1697. self.previewFile(file, theFile, previewId, previewData);
  1698. self.initFileActions();
  1699. };
  1700. reader.onloadend = function () {
  1701. msg = msgProgress
  1702. .repl('{index}', i + 1).repl('{files}', numFiles)
  1703. .repl('{percent}', 50).repl('{name}', caption);
  1704. setTimeout(function () {
  1705. $status.html(msg);
  1706. objUrl.revokeObjectURL(previewData);
  1707. }, 100);
  1708. setTimeout(function () {
  1709. readFile(i + 1);
  1710. self.updateFileDetails(numFiles);
  1711. }, 100);
  1712. self.raise('fileloaded', [file, previewId, i, reader]);
  1713. };
  1714. reader.onprogress = function (data) {
  1715. if (data.lengthComputable) {
  1716. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1717. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1718. .repl('{percent}', progress).repl('{name}', caption);
  1719. setTimeout(function () {
  1720. $status.html(msg);
  1721. }, 100);
  1722. }
  1723. };
  1724. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1725. if (isText(file.type, caption)) {
  1726. reader.readAsText(file, self.textEncoding);
  1727. } else {
  1728. reader.readAsArrayBuffer(file);
  1729. }
  1730. } else {
  1731. self.previewDefault(file, previewId);
  1732. setTimeout(function () {
  1733. readFile(i + 1);
  1734. self.updateFileDetails(numFiles);
  1735. }, 100);
  1736. self.raise('fileloaded', [file, previewId, i, reader]);
  1737. }
  1738. self.filestack.push(file);
  1739. }
  1740. readFile(0);
  1741. self.updateFileDetails(numFiles, false);
  1742. },
  1743. updateFileDetails: function (numFiles) {
  1744. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1745. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1746. n = self.isUploadable ? fileStack.length : numFiles,
  1747. nFiles = previewCache.count(self.id) + n,
  1748. log = n > 1 ? msgSelected.repl('{n}', nFiles) : label;
  1749. if (self.isError) {
  1750. self.$previewContainer.removeClass('loading');
  1751. self.$previewStatus.html('');
  1752. self.$captionContainer.find('.kv-caption-icon').hide();
  1753. } else {
  1754. self.showFileIcon();
  1755. }
  1756. self.setCaption(log, self.isError);
  1757. self.$container.removeClass('file-input-new file-input-ajax-new');
  1758. if (arguments.length === 1) {
  1759. self.raise('fileselect', [numFiles, label]);
  1760. }
  1761. if (previewCache.count(self.id)) {
  1762. self.initPreviewDeletes();
  1763. }
  1764. },
  1765. change: function (e) {
  1766. var self = this, $el = self.$element;
  1767. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1768. self.fileInputCleared = false;
  1769. return;
  1770. }
  1771. self.fileInputCleared = false;
  1772. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1773. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1774. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1775. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr !== 0),
  1776. throwError = function (mesg, file, previewId, index) {
  1777. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1778. p2 = {id: previewId, index: index, file: file, files: files};
  1779. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1780. };
  1781. self.resetUpload();
  1782. self.hideFileIcon();
  1783. if (self.isUploadable) {
  1784. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1785. }
  1786. if (isDragDrop) {
  1787. tfiles = [];
  1788. while (files[i]) {
  1789. f = files[i];
  1790. if (!f.type && f.size % 4096 === 0) {
  1791. folders++;
  1792. } else {
  1793. tfiles.push(f);
  1794. }
  1795. i++;
  1796. }
  1797. } else {
  1798. if (e.target.files === undefined) {
  1799. tfiles = e.target && e.target.value ? [
  1800. {name: e.target.value.replace(/^.+\\/, '')}
  1801. ] : [];
  1802. } else {
  1803. tfiles = e.target.files;
  1804. }
  1805. }
  1806. if (isEmpty(tfiles) || tfiles.length === 0) {
  1807. if (!isAjaxUpload) {
  1808. self.clear();
  1809. }
  1810. self.showFolderError(folders);
  1811. self.raise('fileselectnone');
  1812. return;
  1813. }
  1814. self.resetErrors();
  1815. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1816. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1817. var out = previewCache.out(self.id);
  1818. $preview.html(out.content);
  1819. self.setCaption(out.caption);
  1820. self.initPreviewDeletes();
  1821. } else {
  1822. $preview.html('');
  1823. }
  1824. if (isSingleUpload && ctr > 0) {
  1825. self.filestack = [];
  1826. }
  1827. }
  1828. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1829. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1830. msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total);
  1831. self.isError = throwError(msg, null, null, null);
  1832. self.$captionContainer.find('.kv-caption-icon').hide();
  1833. self.$caption.html(self.msgValidationError);
  1834. self.setEllipsis();
  1835. self.$container.removeClass('file-input-new file-input-ajax-new');
  1836. return;
  1837. }
  1838. if (!self.isIE9) {
  1839. self.readFiles(tfiles);
  1840. } else {
  1841. self.updateFileDetails(1);
  1842. }
  1843. self.showFolderError(folders);
  1844. if (isAjaxUpload) {
  1845. self.raise('filebatchselected', [self.getFileStack()]);
  1846. } else {
  1847. self.raise('filebatchselected', [tfiles]);
  1848. }
  1849. self.reader = null;
  1850. },
  1851. autoSizeImage: function (previewId) {
  1852. var self = this, $preview = self.$preview,
  1853. $thumb = $preview.find("#" + previewId),
  1854. $img = $thumb.find('img'), w1, w2, $cap;
  1855. if (!$img.length) {
  1856. return;
  1857. }
  1858. $img.on('load', function () {
  1859. w1 = $thumb.width();
  1860. w2 = $preview.width();
  1861. if (w1 > w2) {
  1862. $img.css('width', '100%');
  1863. $thumb.css('width', '97%');
  1864. }
  1865. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1866. if ($cap.length) {
  1867. $cap.width($img.width());
  1868. $cap.attr('title', $cap.text());
  1869. }
  1870. self.raise('fileimageloaded', previewId);
  1871. });
  1872. },
  1873. setCaption: function (content, isError) {
  1874. var self = this, err = isError || false, title, out;
  1875. if (isEmpty(content) || self.$caption.length === 0) {
  1876. return;
  1877. }
  1878. if (err) {
  1879. title = $('<div>' + self.msgValidationError + '</div>').text();
  1880. out = '<span class="' + self.msgValidationErrorClass + '">' +
  1881. self.msgValidationErrorIcon + title + '</span>';
  1882. } else {
  1883. title = $('<div>' + content + '</div>').text();
  1884. out = title + self.getLayoutTemplate('icon');
  1885. }
  1886. self.$caption.html(out);
  1887. self.$caption.attr('title', title);
  1888. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1889. self.setEllipsis();
  1890. },
  1891. initBrowse: function ($container) {
  1892. var self = this;
  1893. self.$btnFile = $container.find('.btn-file');
  1894. self.$btnFile.append(self.$element);
  1895. },
  1896. createContainer: function () {
  1897. var self = this,
  1898. $container = $(document.createElement("span"))
  1899. .attr({"class": 'file-input file-input-new'})
  1900. .html(self.renderMain());
  1901. self.$element.before($container);
  1902. self.initBrowse($container);
  1903. return $container;
  1904. },
  1905. refreshContainer: function () {
  1906. var self = this, $container = self.$container;
  1907. $container.before(self.$element);
  1908. $container.html(self.renderMain());
  1909. self.initBrowse($container);
  1910. },
  1911. renderMain: function () {
  1912. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  1913. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  1914. .repl('{dropClass}', dropCss) : '',
  1915. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  1916. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  1917. return self.mainTemplate.repl('{class}', self.mainClass)
  1918. .repl('{preview}', preview)
  1919. .repl('{caption}', caption)
  1920. .repl('{upload}', self.renderUpload())
  1921. .repl('{remove}', self.renderRemove())
  1922. .repl('{cancel}', self.renderCancel())
  1923. .repl('{browse}', self.renderBrowse());
  1924. },
  1925. renderBrowse: function () {
  1926. var self = this, css = self.browseClass + ' btn-file', status = '';
  1927. if (self.isDisabled) {
  1928. status = ' disabled ';
  1929. }
  1930. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1931. },
  1932. renderRemove: function () {
  1933. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1934. if (!self.showRemove) {
  1935. return '';
  1936. }
  1937. if (self.isDisabled) {
  1938. status = ' disabled ';
  1939. }
  1940. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1941. },
  1942. renderCancel: function () {
  1943. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  1944. if (!self.showCancel) {
  1945. return '';
  1946. }
  1947. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1948. },
  1949. renderUpload: function () {
  1950. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1951. if (!self.showUpload) {
  1952. return '';
  1953. }
  1954. if (self.isDisabled) {
  1955. status = ' disabled ';
  1956. }
  1957. if (!self.isUploadable || self.isDisabled) {
  1958. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1959. } else {
  1960. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1961. }
  1962. return content;
  1963. }
  1964. };
  1965. //FileInput plugin definition
  1966. $.fn.fileinput = function (option) {
  1967. if (!hasFileAPISupport() && !isIE(9)) {
  1968. return;
  1969. }
  1970. var args = Array.apply(null, arguments);
  1971. args.shift();
  1972. return this.each(function () {
  1973. var $this = $(this),
  1974. data = $this.data('fileinput'),
  1975. options = typeof option === 'object' && option;
  1976. if (!data) {
  1977. data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()));
  1978. $this.data('fileinput', data);
  1979. }
  1980. if (typeof option === 'string') {
  1981. data[option].apply(data, args);
  1982. }
  1983. });
  1984. };
  1985. $.fn.fileinput.defaults = {
  1986. showCaption: true,
  1987. showPreview: true,
  1988. showRemove: true,
  1989. showUpload: true,
  1990. showCancel: true,
  1991. mainClass: '',
  1992. previewClass: '',
  1993. captionClass: '',
  1994. mainTemplate: null,
  1995. initialCaption: '',
  1996. initialPreview: [],
  1997. initialPreviewDelimiter: '*$$*',
  1998. initialPreviewConfig: [],
  1999. initialPreviewShowDelete: true,
  2000. deleteUrl: '',
  2001. deleteExtraData: {},
  2002. overwriteInitial: true,
  2003. layoutTemplates: defaultLayoutTemplates,
  2004. previewTemplates: defaultPreviewTemplates,
  2005. allowedPreviewTypes: defaultPreviewTypes,
  2006. allowedPreviewMimeTypes: null,
  2007. allowedFileTypes: null,
  2008. allowedFileExtensions: null,
  2009. customLayoutTags: {},
  2010. customPreviewTags: {},
  2011. previewSettings: defaultPreviewSettings,
  2012. fileTypeSettings: defaultFileTypeSettings,
  2013. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2014. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2015. browseClass: 'btn btn-primary',
  2016. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2017. removeClass: 'btn btn-default',
  2018. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2019. cancelClass: 'btn btn-default',
  2020. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2021. uploadClass: 'btn btn-default',
  2022. uploadUrl: null,
  2023. uploadAsync: true,
  2024. uploadExtraData: {},
  2025. maxFileSize: 0,
  2026. minFileCount: 0,
  2027. maxFileCount: 0,
  2028. msgValidationErrorClass: 'text-danger',
  2029. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2030. msgErrorClass: 'file-error-message',
  2031. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2032. progressCompleteClass: "progress-bar progress-bar-success",
  2033. previewFileType: 'image',
  2034. wrapTextLength: 250,
  2035. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2036. elCaptionContainer: null,
  2037. elCaptionText: null,
  2038. elPreviewContainer: null,
  2039. elPreviewImage: null,
  2040. elPreviewStatus: null,
  2041. elErrorContainer: null,
  2042. slugCallback: null,
  2043. dropZoneEnabled: true,
  2044. dropZoneTitleClass: 'file-drop-zone-title',
  2045. fileActionSettings: {},
  2046. otherActionButtons: '',
  2047. textEncoding: 'UTF-8',
  2048. ajaxSettings: {},
  2049. ajaxDeleteSettings: {},
  2050. showAjaxErrorDetails: true
  2051. };
  2052. $.fn.fileinput.locales = {};
  2053. $.fn.fileinput.locales.en = {
  2054. fileSingle: 'file',
  2055. filePlural: 'files',
  2056. browseLabel: 'Browse &hellip;',
  2057. removeLabel: 'Remove',
  2058. removeTitle: 'Clear selected files',
  2059. cancelLabel: 'Cancel',
  2060. cancelTitle: 'Abort ongoing upload',
  2061. uploadLabel: 'Upload',
  2062. uploadTitle: 'Upload selected files',
  2063. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2064. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2065. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2066. msgFileNotFound: 'File "{name}" not found!',
  2067. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2068. msgFileNotReadable: 'File "{name}" is not readable.',
  2069. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2070. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2071. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2072. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2073. msgValidationError: 'File Upload Error',
  2074. msgLoading: 'Loading file {index} of {files} &hellip;',
  2075. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2076. msgSelected: '{n} files selected',
  2077. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2078. dropZoneTitle: 'Drag & drop files here &hellip;'
  2079. };
  2080. $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.en);
  2081. $.fn.fileinput.Constructor = FileInput;
  2082. /**
  2083. * Convert automatically file inputs with class 'file'
  2084. * into a bootstrap fileinput control.
  2085. */
  2086. $(document).ready(function () {
  2087. var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0;
  2088. if (count > 0) {
  2089. $input.fileinput();
  2090. }
  2091. });
  2092. })(window.jQuery);