fileinput.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  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. self.$btnUpload.removeAttr('disabled');
  1024. self.resetUpload();
  1025. self.filestack = [];
  1026. self.clearFileInput();
  1027. self.resetErrors(true);
  1028. self.raise('fileclear');
  1029. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1030. self.showFileIcon();
  1031. self.resetPreview();
  1032. self.setEllipsis();
  1033. self.initPreviewDeletes();
  1034. self.$container.removeClass('file-input-new');
  1035. } else {
  1036. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1037. self.clearObjects($(this));
  1038. });
  1039. self.$preview.html('');
  1040. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1041. self.$caption.html(cap);
  1042. self.setEllipsis();
  1043. self.$caption.attr('title', '');
  1044. addCss(self.$container, 'file-input-new');
  1045. }
  1046. if (self.$container.find('.file-preview-frame').length === 0) {
  1047. self.initialCaption = '';
  1048. self.$caption.html('');
  1049. self.setEllipsis();
  1050. self.$captionContainer.find('.kv-caption-icon').hide();
  1051. }
  1052. self.hideFileIcon();
  1053. self.raise('filecleared');
  1054. self.$captionContainer.focus();
  1055. self.setFileDropZoneTitle();
  1056. },
  1057. resetPreview: function () {
  1058. var self = this, out;
  1059. if (previewCache.count(self.id)) {
  1060. out = previewCache.out(self.id);
  1061. self.$preview.html(out.content);
  1062. self.setCaption(out.caption);
  1063. } else {
  1064. self.$preview.html('');
  1065. self.$caption.html('');
  1066. }
  1067. },
  1068. reset: function () {
  1069. var self = this;
  1070. self.clear();
  1071. self.resetPreview();
  1072. self.setEllipsis();
  1073. self.$container.find('.fileinput-filename').text('');
  1074. self.raise('filereset');
  1075. if (self.initialPreview.length > 0) {
  1076. self.$container.removeClass('file-input-new');
  1077. }
  1078. self.setFileDropZoneTitle();
  1079. self.filestack = [];
  1080. self.formdata = {};
  1081. },
  1082. disable: function () {
  1083. var self = this;
  1084. self.isDisabled = true;
  1085. self.raise('filedisabled');
  1086. self.$element.attr('disabled', 'disabled');
  1087. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1088. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  1089. self.initDragDrop();
  1090. },
  1091. enable: function () {
  1092. var self = this;
  1093. self.isDisabled = false;
  1094. self.raise('fileenabled');
  1095. self.$element.removeAttr('disabled');
  1096. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1097. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  1098. self.initDragDrop();
  1099. },
  1100. getExtraData: function () {
  1101. var self = this, data = self.uploadExtraData;
  1102. if (typeof self.uploadExtraData === "function") {
  1103. data = self.uploadExtraData();
  1104. }
  1105. return data;
  1106. },
  1107. uploadExtra: function () {
  1108. var self = this, data = self.getExtraData();
  1109. if (data.length === 0) {
  1110. return;
  1111. }
  1112. $.each(data, function (key, value) {
  1113. self.formdata.append(key, value);
  1114. });
  1115. },
  1116. initXhr: function (xhrobj, factor) {
  1117. var self = this;
  1118. if (xhrobj.upload) {
  1119. xhrobj.upload.addEventListener('progress', function (event) {
  1120. var pct = 0, position = event.loaded || event.position, total = event.total;
  1121. if (event.lengthComputable) {
  1122. pct = Math.ceil(position / total * factor);
  1123. }
  1124. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1125. self.setProgress(self.uploadPercent);
  1126. }, false);
  1127. }
  1128. return xhrobj;
  1129. },
  1130. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  1131. var self = this, settings;
  1132. self.uploadExtra();
  1133. settings = $.extend({
  1134. xhr: function () {
  1135. var xhrobj = $.ajaxSettings.xhr();
  1136. return self.initXhr(xhrobj, 98);
  1137. },
  1138. url: self.uploadUrl,
  1139. type: 'POST',
  1140. dataType: 'json',
  1141. data: self.formdata,
  1142. cache: false,
  1143. processData: false,
  1144. contentType: false,
  1145. beforeSend: fnBefore,
  1146. success: fnSuccess,
  1147. complete: fnComplete,
  1148. error: fnError
  1149. }, self.ajaxSettings);
  1150. self.ajaxRequests.push($.ajax(settings));
  1151. },
  1152. initUploadSuccess: function (out, $thumb, allFiles) {
  1153. var self = this, append, data, index, $newThumb, content, config;
  1154. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1155. return;
  1156. }
  1157. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1158. self.hasInitData = true;
  1159. content = out.initialPreview || [];
  1160. config = out.initialPreviewConfig || [];
  1161. append = out.append === undefined || out.append ? true : false;
  1162. self.overwriteInitial = false;
  1163. if ($thumb !== undefined && !!allFiles) {
  1164. index = previewCache.add(self.id, content, config[0], append);
  1165. data = previewCache.get(self.id, index, false);
  1166. $newThumb = $(data).hide();
  1167. $thumb.after($newThumb).fadeOut('slow', function () {
  1168. $newThumb.fadeIn('slow').css('display:inline-block');
  1169. self.initPreviewDeletes();
  1170. });
  1171. } else {
  1172. if (allFiles) {
  1173. self.uploadCache.content.push(content[0]);
  1174. self.uploadCache.config.push(config[0]);
  1175. self.uploadCache.append = append;
  1176. } else {
  1177. previewCache.set(self.id, content, config, append);
  1178. self.initPreview();
  1179. self.initPreviewDeletes();
  1180. }
  1181. }
  1182. }
  1183. },
  1184. uploadSingle: function (i, files, allFiles) {
  1185. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1186. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1187. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1188. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  1189. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1190. setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError,
  1191. params = {id: previewId, index: i};
  1192. self.formdata = formdata;
  1193. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1194. return;
  1195. }
  1196. chkComplete = function () {
  1197. var $thumbs = self.$preview.find(PREVIEW_FRAMES + '.file-uploading');
  1198. if ($thumbs.length > 0 && self.fileBatchCompleted) {
  1199. return;
  1200. }
  1201. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.append);
  1202. if (self.hasInitData) {
  1203. self.initPreview();
  1204. self.initPreviewDeletes();
  1205. }
  1206. self.setProgress(100);
  1207. self.unlock();
  1208. self.clearFileInput();
  1209. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1210. self.fileBatchCompleted = true;
  1211. };
  1212. setIndicator = function (icon, msg) {
  1213. $indicator.html(config[icon]);
  1214. $indicator.attr('title', config[msg]);
  1215. };
  1216. updateProgress = function () {
  1217. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1218. return;
  1219. }
  1220. self.uploadCount += 1;
  1221. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1222. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1223. self.setProgress(self.uploadPercent);
  1224. self.initPreviewDeletes();
  1225. };
  1226. resetActions = function () {
  1227. $btnUpload.removeAttr('disabled');
  1228. $btnDelete.removeAttr('disabled');
  1229. $thumb.removeClass('file-uploading');
  1230. };
  1231. fnBefore = function (jqXHR) {
  1232. outData = self.getOutData(jqXHR);
  1233. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  1234. addCss($thumb, 'file-uploading');
  1235. $btnUpload.attr('disabled', true);
  1236. $btnDelete.attr('disabled', true);
  1237. if (!allFiles) {
  1238. self.lock();
  1239. }
  1240. self.raise('filepreupload', [outData, previewId, i]);
  1241. params = $.extend(params, outData);
  1242. if (self.abort(params)) {
  1243. jqXHR.abort();
  1244. self.setProgress(100);
  1245. }
  1246. };
  1247. fnSuccess = function (data, textStatus, jqXHR) {
  1248. outData = self.getOutData(jqXHR, data);
  1249. params = $.extend(params, outData);
  1250. setTimeout(function () {
  1251. if (data.error === undefined) {
  1252. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  1253. $btnUpload.hide();
  1254. $btnDelete.hide();
  1255. self.filestack[i] = undefined;
  1256. self.raise('fileuploaded', [outData, previewId, i]);
  1257. self.initUploadSuccess(data, $thumb, allFiles);
  1258. if (!allFiles) {
  1259. self.resetFileStack();
  1260. }
  1261. } else {
  1262. setIndicator('indicatorError', 'indicatorErrorTitle');
  1263. self.showUploadError(data.error, params);
  1264. }
  1265. }, 100);
  1266. };
  1267. fnComplete = function () {
  1268. setTimeout(function () {
  1269. updateProgress();
  1270. resetActions();
  1271. if (!allFiles) {
  1272. self.unlock(false);
  1273. } else {
  1274. setTimeout(function () {
  1275. chkComplete();
  1276. }, 500);
  1277. }
  1278. }, 100);
  1279. };
  1280. fnError = function (jqXHR, textStatus, errorThrown) {
  1281. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1282. setIndicator('indicatorError', 'indicatorErrorTitle');
  1283. params = $.extend(params, self.getOutData(jqXHR));
  1284. self.showUploadError(errMsg, params);
  1285. };
  1286. formdata.append(self.uploadFileAttr, files[i]);
  1287. formdata.append('file_id', i);
  1288. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1289. },
  1290. uploadBatch: function () {
  1291. var self = this, files = self.filestack, total = files.length, config,
  1292. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1293. setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1294. params = {};
  1295. self.formdata = new FormData();
  1296. if (total === 0 || !hasPostData || self.abort(params)) {
  1297. return;
  1298. }
  1299. config = self.fileActionSettings;
  1300. setIndicator = function (i, icon, msg) {
  1301. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1302. $indicator.html(config[icon]);
  1303. $indicator.attr('title', config[msg]);
  1304. };
  1305. enableActions = function (i) {
  1306. var $thumb = $('#' + self.previewInitId + "-" + i + ':not(.file-preview-initial)'),
  1307. $btnUpload = $thumb.find('.kv-file-upload'),
  1308. $btnDelete = $thumb.find('.kv-file-delete');
  1309. $thumb.removeClass('file-uploading');
  1310. $btnUpload.removeAttr('disabled');
  1311. $btnDelete.removeAttr('disabled');
  1312. };
  1313. setAllUploaded = function () {
  1314. $.each(files, function (key, data) {
  1315. self.filestack[key] = undefined;
  1316. });
  1317. self.clearFileInput();
  1318. };
  1319. fnBefore = function (jqXHR) {
  1320. self.lock();
  1321. var outData = self.getOutData(jqXHR);
  1322. if (self.showPreview) {
  1323. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1324. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1325. addCss($thumb, 'file-uploading');
  1326. $btnUpload.attr('disabled', true);
  1327. $btnDelete.attr('disabled', true);
  1328. });
  1329. }
  1330. self.raise('filebatchpreupload', [outData]);
  1331. if (self.abort(outData)) {
  1332. jqXHR.abort();
  1333. }
  1334. };
  1335. fnSuccess = function (data, textStatus, jqXHR) {
  1336. var outData = self.getOutData(jqXHR, data),
  1337. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1338. if (data.error === undefined || isEmpty(data.error)) {
  1339. self.raise('filebatchuploadsuccess', [outData]);
  1340. setAllUploaded();
  1341. if (self.showPreview) {
  1342. self.$preview.find('.kv-file-upload').hide();
  1343. self.$preview.find('.kv-file-remove').hide();
  1344. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1345. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1346. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1347. enableActions(key);
  1348. });
  1349. self.initUploadSuccess(data);
  1350. } else {
  1351. self.reset();
  1352. }
  1353. } else {
  1354. if (self.showPreview) {
  1355. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1356. var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10);
  1357. enableActions(key);
  1358. if (keys.length === 0) {
  1359. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1360. return;
  1361. }
  1362. if ($.inArray(key, keys) !== -1) {
  1363. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1364. } else {
  1365. $thumb.find('.kv-file-upload').hide();
  1366. $thumb.find('.kv-file-remove').hide();
  1367. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1368. self.filestack[key] = undefined;
  1369. }
  1370. });
  1371. self.initUploadSuccess(data);
  1372. }
  1373. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1374. }
  1375. };
  1376. fnComplete = function () {
  1377. self.setProgress(100);
  1378. self.unlock();
  1379. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1380. self.clearFileInput();
  1381. };
  1382. fnError = function (jqXHR, textStatus, errorThrown) {
  1383. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1384. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1385. self.uploadFileCount = total - 1;
  1386. if (!self.showPreview) {
  1387. return;
  1388. }
  1389. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1390. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1391. $thumb.removeClass('file-uploading');
  1392. if (self.filestack[key] !== undefined) {
  1393. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1394. }
  1395. });
  1396. self.$preview.find(PREVIEW_FRAMES).removeClass('file-uploading');
  1397. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-upload').removeAttr('disabled');
  1398. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-delete').removeAttr('disabled');
  1399. };
  1400. $.each(files, function (key, data) {
  1401. if (!isEmpty(files[key])) {
  1402. self.formdata.append(self.uploadFileAttr, data);
  1403. }
  1404. });
  1405. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1406. },
  1407. uploadExtraOnly: function () {
  1408. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1409. self.formdata = new FormData();
  1410. if (self.abort(params)) {
  1411. return;
  1412. }
  1413. fnBefore = function (jqXHR) {
  1414. self.lock();
  1415. var outData = self.getOutData(jqXHR);
  1416. self.raise('filebatchpreupload', [outData]);
  1417. self.setProgress(50);
  1418. params.data = outData;
  1419. params.xhr = jqXHR;
  1420. if (self.abort(params)) {
  1421. jqXHR.abort();
  1422. self.setProgress(100);
  1423. }
  1424. };
  1425. fnSuccess = function (data, textStatus, jqXHR) {
  1426. var outData = self.getOutData(jqXHR, data);
  1427. if (data.error === undefined || isEmpty(data.error)) {
  1428. self.raise('filebatchuploadsuccess', [outData]);
  1429. self.clearFileInput();
  1430. self.initUploadSuccess(data);
  1431. } else {
  1432. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1433. }
  1434. };
  1435. fnComplete = function () {
  1436. self.setProgress(100);
  1437. self.unlock();
  1438. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1439. self.clearFileInput();
  1440. };
  1441. fnError = function (jqXHR, textStatus, errorThrown) {
  1442. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1443. params.data = outData;
  1444. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1445. };
  1446. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1447. },
  1448. hideFileIcon: function () {
  1449. if (this.overwriteInitial) {
  1450. this.$captionContainer.find('.kv-caption-icon').hide();
  1451. }
  1452. },
  1453. showFileIcon: function () {
  1454. this.$captionContainer.find('.kv-caption-icon').show();
  1455. },
  1456. resetErrors: function (fade) {
  1457. var self = this, $error = self.$errorContainer;
  1458. self.isError = false;
  1459. self.$container.removeClass('has-error');
  1460. $error.html('');
  1461. if (fade) {
  1462. $error.fadeOut('slow');
  1463. } else {
  1464. $error.hide();
  1465. }
  1466. },
  1467. showFolderError: function (folders) {
  1468. var self = this, $error = self.$errorContainer;
  1469. if (!folders) {
  1470. return;
  1471. }
  1472. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1473. $error.fadeIn(800);
  1474. addCss(self.$container, 'has-error');
  1475. self.raise('filefoldererror', [folders]);
  1476. },
  1477. showUploadError: function (msg, params, event) {
  1478. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1479. if ($error.find('ul').length === 0) {
  1480. $error.html('<ul><li>' + msg + '</li></ul>');
  1481. } else {
  1482. $error.find('ul').append('<li>' + msg + '</li>');
  1483. }
  1484. $error.fadeIn(800);
  1485. self.raise(ev, [params]);
  1486. addCss(self.$container, 'has-error');
  1487. return true;
  1488. },
  1489. showError: function (msg, params, event) {
  1490. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1491. params = params || {};
  1492. params.reader = self.reader;
  1493. $error.html(msg);
  1494. $error.fadeIn(800);
  1495. self.raise(ev, [params]);
  1496. if (!self.isUploadable) {
  1497. self.clearFileInput();
  1498. }
  1499. addCss(self.$container, 'has-error');
  1500. self.$btnUpload.attr('disabled', true);
  1501. return true;
  1502. },
  1503. errorHandler: function (evt, caption) {
  1504. var self = this, err = evt.target.error;
  1505. switch (err.code) {
  1506. case err.NOT_FOUND_ERR:
  1507. self.showError(self.msgFileNotFound.repl('{name}', caption));
  1508. break;
  1509. case err.SECURITY_ERR:
  1510. self.showError(self.msgFileSecured.repl('{name}', caption));
  1511. break;
  1512. case err.NOT_READABLE_ERR:
  1513. self.showError(self.msgFileNotReadable.repl('{name}', caption));
  1514. break;
  1515. case err.ABORT_ERR:
  1516. self.showError(self.msgFilePreviewAborted.repl('{name}', caption));
  1517. break;
  1518. default:
  1519. self.showError(self.msgFilePreviewError.repl('{name}', caption));
  1520. }
  1521. },
  1522. parseFileType: function (file) {
  1523. var self = this, isValid, vType, cat, i;
  1524. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1525. cat = defaultPreviewTypes[i];
  1526. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1527. vType = isValid(file.type, file.name) ? cat : '';
  1528. if (!isEmpty(vType)) {
  1529. return vType;
  1530. }
  1531. }
  1532. return 'other';
  1533. },
  1534. previewDefault: function (file, previewId, isDisabled) {
  1535. if (!this.showPreview) {
  1536. return;
  1537. }
  1538. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1539. config = self.previewSettings.other,
  1540. footer = self.renderFileFooter(file.name, config.width),
  1541. previewOtherTemplate = self.getPreviewTemplate('other'),
  1542. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1543. frameClass = '';
  1544. if (isDisabled === true) {
  1545. frameClass = ' btn disabled';
  1546. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1547. }
  1548. self.$preview.append("\n" + previewOtherTemplate
  1549. .repl('{previewId}', previewId)
  1550. .repl('{frameClass}', frameClass)
  1551. .repl('{fileindex}', ind)
  1552. .repl('{caption}', self.slug(file.name))
  1553. .repl('{width}', config.width)
  1554. .repl('{height}', config.height)
  1555. .repl('{type}', file.type)
  1556. .repl('{data}', data)
  1557. .repl('{footer}', footer));
  1558. $obj.on('load', function () {
  1559. objUrl.revokeObjectURL($obj.attr('data'));
  1560. });
  1561. },
  1562. previewFile: function (file, theFile, previewId, data) {
  1563. if (!this.showPreview) {
  1564. return;
  1565. }
  1566. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1567. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1568. tmplt = self.getPreviewTemplate(cat),
  1569. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1570. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1571. chkTypes = types.indexOf(cat) >= 0, id, height,
  1572. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1573. footer = self.renderFileFooter(caption, config.width), modal = '',
  1574. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1575. if (chkTypes && chkMimes) {
  1576. if (cat === 'text') {
  1577. strText = htmlEncode(theFile.target.result);
  1578. objUrl.revokeObjectURL(data);
  1579. if (strText.length > wrapLen) {
  1580. id = 'text-' + uniqId();
  1581. height = window.innerHeight * 0.75;
  1582. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1583. .repl('{title}', caption)
  1584. .repl('{height}', height)
  1585. .repl('{body}', strText);
  1586. wrapInd = wrapInd
  1587. .repl('{title}', caption)
  1588. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1589. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1590. }
  1591. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1592. .repl('{frameClass}', '')
  1593. .repl('{type}', file.type).repl('{width}', config.width)
  1594. .repl('{height}', config.height).repl('{data}', strText)
  1595. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1596. } else {
  1597. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1598. .repl('{frameClass}', '')
  1599. .repl('{type}', file.type).repl('{data}', data)
  1600. .repl('{width}', config.width).repl('{height}', config.height)
  1601. .repl('{footer}', footer).repl('{fileindex}', ind);
  1602. }
  1603. self.$preview.append("\n" + content);
  1604. self.autoSizeImage(previewId);
  1605. } else {
  1606. self.previewDefault(file, previewId);
  1607. }
  1608. },
  1609. slugDefault: function (text) {
  1610. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\-.\\\/ ]+/g, '');
  1611. },
  1612. getFileStack: function () {
  1613. var self = this;
  1614. return self.filestack.filter(function (n) {
  1615. return n !== undefined;
  1616. });
  1617. },
  1618. readFiles: function (files) {
  1619. this.reader = new FileReader();
  1620. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1621. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1622. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1623. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1624. throwError = function (msg, file, previewId, index) {
  1625. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1626. p2 = {id: previewId, index: index, file: file, files: files};
  1627. self.previewDefault(file, previewId, true);
  1628. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1629. };
  1630. function readFile(i) {
  1631. if (isEmpty($el.attr('multiple'))) {
  1632. numFiles = 1;
  1633. }
  1634. if (i >= numFiles) {
  1635. if (self.isUploadable && self.filestack.length > 0) {
  1636. self.raise('filebatchselected', [self.getFileStack()]);
  1637. } else {
  1638. self.raise('filebatchselected', [tfiles]);
  1639. }
  1640. $container.removeClass('loading');
  1641. $status.html('');
  1642. return;
  1643. }
  1644. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1645. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1646. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1647. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1648. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1649. if (!isEmpty(fileExt)) {
  1650. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1651. }
  1652. fileSize = fileSize.toFixed(2);
  1653. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1654. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1655. .repl('{size}', fileSize)
  1656. .repl('{maxSize}', self.maxFileSize);
  1657. self.isError = throwError(msg, file, previewId, i);
  1658. return;
  1659. }
  1660. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1661. for (j = 0; j < fileTypes.length; j += 1) {
  1662. typ = fileTypes[j];
  1663. checkFile = settings[typ];
  1664. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1665. fileCount += isEmpty(chk) ? 0 : chk.length;
  1666. }
  1667. if (fileCount === 0) {
  1668. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1669. self.isError = throwError(msg, file, previewId, i);
  1670. return;
  1671. }
  1672. }
  1673. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1674. chk = caption.match(fileExtExpr);
  1675. fileCount += isEmpty(chk) ? 0 : chk.length;
  1676. if (fileCount === 0) {
  1677. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1678. strExt);
  1679. self.isError = throwError(msg, file, previewId, i);
  1680. return;
  1681. }
  1682. }
  1683. if (!self.showPreview) {
  1684. self.filestack.push(file);
  1685. setTimeout(readFile(i + 1), 100);
  1686. self.raise('fileloaded', [file, previewId, i, reader]);
  1687. return;
  1688. }
  1689. if ($preview.length > 0 && FileReader !== undefined) {
  1690. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1691. $container.addClass('loading');
  1692. reader.onerror = function (evt) {
  1693. self.errorHandler(evt, caption);
  1694. };
  1695. reader.onload = function (theFile) {
  1696. self.previewFile(file, theFile, previewId, previewData);
  1697. self.initFileActions();
  1698. };
  1699. reader.onloadend = function () {
  1700. msg = msgProgress
  1701. .repl('{index}', i + 1).repl('{files}', numFiles)
  1702. .repl('{percent}', 50).repl('{name}', caption);
  1703. setTimeout(function () {
  1704. $status.html(msg);
  1705. objUrl.revokeObjectURL(previewData);
  1706. }, 100);
  1707. setTimeout(function () {
  1708. readFile(i + 1);
  1709. self.updateFileDetails(numFiles);
  1710. }, 100);
  1711. self.raise('fileloaded', [file, previewId, i, reader]);
  1712. };
  1713. reader.onprogress = function (data) {
  1714. if (data.lengthComputable) {
  1715. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1716. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1717. .repl('{percent}', progress).repl('{name}', caption);
  1718. setTimeout(function () {
  1719. $status.html(msg);
  1720. }, 100);
  1721. }
  1722. };
  1723. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1724. if (isText(file.type, caption)) {
  1725. reader.readAsText(file, self.textEncoding);
  1726. } else {
  1727. reader.readAsArrayBuffer(file);
  1728. }
  1729. } else {
  1730. self.previewDefault(file, previewId);
  1731. setTimeout(function () {
  1732. readFile(i + 1);
  1733. self.updateFileDetails(numFiles);
  1734. }, 100);
  1735. self.raise('fileloaded', [file, previewId, i, reader]);
  1736. }
  1737. self.filestack.push(file);
  1738. }
  1739. readFile(0);
  1740. self.updateFileDetails(numFiles, false);
  1741. },
  1742. updateFileDetails: function (numFiles) {
  1743. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1744. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1745. n = self.isUploadable ? fileStack.length : numFiles,
  1746. nFiles = previewCache.count(self.id) + n,
  1747. log = n > 1 ? msgSelected.repl('{n}', nFiles) : label;
  1748. if (self.isError) {
  1749. self.$previewContainer.removeClass('loading');
  1750. self.$previewStatus.html('');
  1751. self.$captionContainer.find('.kv-caption-icon').hide();
  1752. } else {
  1753. self.showFileIcon();
  1754. }
  1755. self.setCaption(log, self.isError);
  1756. self.$container.removeClass('file-input-new file-input-ajax-new');
  1757. if (arguments.length === 1) {
  1758. self.raise('fileselect', [numFiles, label]);
  1759. }
  1760. if (previewCache.count(self.id)) {
  1761. self.initPreviewDeletes();
  1762. }
  1763. },
  1764. change: function (e) {
  1765. var self = this, $el = self.$element;
  1766. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1767. self.fileInputCleared = false;
  1768. return;
  1769. }
  1770. self.fileInputCleared = false;
  1771. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1772. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1773. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1774. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr !== 0),
  1775. throwError = function (mesg, file, previewId, index) {
  1776. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1777. p2 = {id: previewId, index: index, file: file, files: files};
  1778. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1779. };
  1780. self.reader = null;
  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. },
  1845. autoSizeImage: function (previewId) {
  1846. var self = this, $preview = self.$preview,
  1847. $thumb = $preview.find("#" + previewId),
  1848. $img = $thumb.find('img'), w1, w2, $cap;
  1849. if (!$img.length) {
  1850. return;
  1851. }
  1852. $img.on('load', function () {
  1853. w1 = $thumb.width();
  1854. w2 = $preview.width();
  1855. if (w1 > w2) {
  1856. $img.css('width', '100%');
  1857. $thumb.css('width', '97%');
  1858. }
  1859. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1860. if ($cap.length) {
  1861. $cap.width($img.width());
  1862. $cap.attr('title', $cap.text());
  1863. }
  1864. self.raise('fileimageloaded', previewId);
  1865. });
  1866. },
  1867. setCaption: function (content, isError) {
  1868. var self = this, err = isError || false, title, out;
  1869. if (isEmpty(content) || self.$caption.length === 0) {
  1870. return;
  1871. }
  1872. if (err) {
  1873. title = $('<div>' + self.msgValidationError + '</div>').text();
  1874. out = '<span class="' + self.msgValidationErrorClass + '">' +
  1875. self.msgValidationErrorIcon + title + '</span>';
  1876. } else {
  1877. title = $('<div>' + content + '</div>').text();
  1878. out = title + self.getLayoutTemplate('icon');
  1879. }
  1880. self.$caption.html(out);
  1881. self.$caption.attr('title', title);
  1882. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1883. self.setEllipsis();
  1884. },
  1885. initBrowse: function ($container) {
  1886. var self = this;
  1887. self.$btnFile = $container.find('.btn-file');
  1888. self.$btnFile.append(self.$element);
  1889. },
  1890. createContainer: function () {
  1891. var self = this,
  1892. $container = $(document.createElement("span"))
  1893. .attr({"class": 'file-input file-input-new'})
  1894. .html(self.renderMain());
  1895. self.$element.before($container);
  1896. self.initBrowse($container);
  1897. return $container;
  1898. },
  1899. refreshContainer: function () {
  1900. var self = this, $container = self.$container;
  1901. $container.before(self.$element);
  1902. $container.html(self.renderMain());
  1903. self.initBrowse($container);
  1904. },
  1905. renderMain: function () {
  1906. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  1907. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  1908. .repl('{dropClass}', dropCss) : '',
  1909. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  1910. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  1911. return self.mainTemplate.repl('{class}', self.mainClass)
  1912. .repl('{preview}', preview)
  1913. .repl('{caption}', caption)
  1914. .repl('{upload}', self.renderUpload())
  1915. .repl('{remove}', self.renderRemove())
  1916. .repl('{cancel}', self.renderCancel())
  1917. .repl('{browse}', self.renderBrowse());
  1918. },
  1919. renderBrowse: function () {
  1920. var self = this, css = self.browseClass + ' btn-file', status = '';
  1921. if (self.isDisabled) {
  1922. status = ' disabled ';
  1923. }
  1924. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1925. },
  1926. renderRemove: function () {
  1927. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1928. if (!self.showRemove) {
  1929. return '';
  1930. }
  1931. if (self.isDisabled) {
  1932. status = ' disabled ';
  1933. }
  1934. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1935. },
  1936. renderCancel: function () {
  1937. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  1938. if (!self.showCancel) {
  1939. return '';
  1940. }
  1941. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1942. },
  1943. renderUpload: function () {
  1944. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1945. if (!self.showUpload) {
  1946. return '';
  1947. }
  1948. if (self.isDisabled) {
  1949. status = ' disabled ';
  1950. }
  1951. if (!self.isUploadable || self.isDisabled) {
  1952. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1953. } else {
  1954. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1955. }
  1956. return content;
  1957. }
  1958. };
  1959. //FileInput plugin definition
  1960. $.fn.fileinput = function (option) {
  1961. if (!hasFileAPISupport() && !isIE(9)) {
  1962. return;
  1963. }
  1964. var args = Array.apply(null, arguments);
  1965. args.shift();
  1966. return this.each(function () {
  1967. var $this = $(this),
  1968. data = $this.data('fileinput'),
  1969. options = typeof option === 'object' && option;
  1970. if (!data) {
  1971. data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()));
  1972. $this.data('fileinput', data);
  1973. }
  1974. if (typeof option === 'string') {
  1975. data[option].apply(data, args);
  1976. }
  1977. });
  1978. };
  1979. $.fn.fileinput.defaults = {
  1980. showCaption: true,
  1981. showPreview: true,
  1982. showRemove: true,
  1983. showUpload: true,
  1984. showCancel: true,
  1985. mainClass: '',
  1986. previewClass: '',
  1987. captionClass: '',
  1988. mainTemplate: null,
  1989. initialCaption: '',
  1990. initialPreview: [],
  1991. initialPreviewDelimiter: '*$$*',
  1992. initialPreviewConfig: [],
  1993. initialPreviewShowDelete: true,
  1994. deleteUrl: '',
  1995. deleteExtraData: {},
  1996. overwriteInitial: true,
  1997. layoutTemplates: defaultLayoutTemplates,
  1998. previewTemplates: defaultPreviewTemplates,
  1999. allowedPreviewTypes: defaultPreviewTypes,
  2000. allowedPreviewMimeTypes: null,
  2001. allowedFileTypes: null,
  2002. allowedFileExtensions: null,
  2003. customLayoutTags: {},
  2004. customPreviewTags: {},
  2005. previewSettings: defaultPreviewSettings,
  2006. fileTypeSettings: defaultFileTypeSettings,
  2007. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2008. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2009. browseClass: 'btn btn-primary',
  2010. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2011. removeClass: 'btn btn-default',
  2012. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2013. cancelClass: 'btn btn-default',
  2014. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2015. uploadClass: 'btn btn-default',
  2016. uploadUrl: null,
  2017. uploadAsync: true,
  2018. uploadExtraData: {},
  2019. maxFileSize: 0,
  2020. minFileCount: 0,
  2021. maxFileCount: 0,
  2022. msgValidationErrorClass: 'text-danger',
  2023. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2024. msgErrorClass: 'file-error-message',
  2025. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2026. progressCompleteClass: "progress-bar progress-bar-success",
  2027. previewFileType: 'image',
  2028. wrapTextLength: 250,
  2029. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2030. elCaptionContainer: null,
  2031. elCaptionText: null,
  2032. elPreviewContainer: null,
  2033. elPreviewImage: null,
  2034. elPreviewStatus: null,
  2035. elErrorContainer: null,
  2036. slugCallback: null,
  2037. dropZoneEnabled: true,
  2038. dropZoneTitleClass: 'file-drop-zone-title',
  2039. fileActionSettings: {},
  2040. otherActionButtons: '',
  2041. textEncoding: 'UTF-8',
  2042. ajaxSettings: {},
  2043. ajaxDeleteSettings: {},
  2044. showAjaxErrorDetails: true
  2045. };
  2046. $.fn.fileinput.locales = {};
  2047. $.fn.fileinput.locales.en = {
  2048. fileSingle: 'file',
  2049. filePlural: 'files',
  2050. browseLabel: 'Browse &hellip;',
  2051. removeLabel: 'Remove',
  2052. removeTitle: 'Clear selected files',
  2053. cancelLabel: 'Cancel',
  2054. cancelTitle: 'Abort ongoing upload',
  2055. uploadLabel: 'Upload',
  2056. uploadTitle: 'Upload selected files',
  2057. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2058. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2059. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2060. msgFileNotFound: 'File "{name}" not found!',
  2061. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2062. msgFileNotReadable: 'File "{name}" is not readable.',
  2063. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2064. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2065. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2066. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2067. msgValidationError: 'File Upload Error',
  2068. msgLoading: 'Loading file {index} of {files} &hellip;',
  2069. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2070. msgSelected: '{n} files selected',
  2071. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2072. dropZoneTitle: 'Drag & drop files here &hellip;'
  2073. };
  2074. $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.en);
  2075. $.fn.fileinput.Constructor = FileInput;
  2076. /**
  2077. * Convert automatically file inputs with class 'file'
  2078. * into a bootstrap fileinput control.
  2079. */
  2080. $(document).ready(function () {
  2081. var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0;
  2082. if (count > 0) {
  2083. $input.fileinput();
  2084. }
  2085. });
  2086. })(window.jQuery);