fileinput.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103
  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. delete previewCache.data[id];
  116. return;
  117. }
  118. previewCache.data[id].content[index] = undefined;
  119. previewCache.data[id].config[index] = undefined;
  120. },
  121. out: function (id) {
  122. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id);
  123. if (len === 0) {
  124. return {content: '', caption: ''};
  125. }
  126. for (var i = 0; i < len; i++) {
  127. html += previewCache.get(id, i);
  128. }
  129. caption = data.msg.repl('{n}', len);
  130. return {content: html, caption: caption};
  131. },
  132. footer: function (id, i, isDisabled) {
  133. var data = previewCache.data[id];
  134. isDisabled = isDisabled === undefined ? true : isDisabled;
  135. if (data.config.length === 0 || isEmpty(data.config[i])) {
  136. return '';
  137. }
  138. var config = data.config[i],
  139. caption = isSet('caption', config) ? config.caption : '',
  140. width = isSet('width', config) ? config.width : 'auto',
  141. url = isSet('url', config) ? config.url : false,
  142. key = isSet('key', config) ? config.key : null,
  143. disabled = (url === false) && isDisabled,
  144. actions = data.isDelete ? data.actions(false, true, disabled, url, key, i) : '',
  145. footer = data.footer.repl('{actions}', actions);
  146. return footer
  147. .repl('{caption}', caption)
  148. .repl('{width}', width)
  149. .repl('{indicator}', '')
  150. .repl('{indicatorTitle}', '');
  151. }
  152. },
  153. PREVIEW_FRAMES = '.file-preview-frame:not(.file-preview-initial)',
  154. getNum = function (num, def) {
  155. def = def || 0;
  156. if (typeof num === "number") {
  157. return num;
  158. }
  159. if (typeof num === "string") {
  160. num = parseFloat(num);
  161. }
  162. return isNaN(num) ? def : num;
  163. },
  164. hasFileAPISupport = function () {
  165. return window.File && window.FileReader;
  166. },
  167. hasDragDropSupport = function () {
  168. var $div = document.createElement('div');
  169. return !isIE(9) && ($div.draggable !== undefined || ($div.ondragstart !== undefined && $div.ondrop !== undefined));
  170. },
  171. hasFileUploadSupport = function () {
  172. return hasFileAPISupport && window.FormData;
  173. },
  174. addCss = function ($el, css) {
  175. $el.removeClass(css).addClass(css);
  176. },
  177. STYLE_SETTING = 'style="width:{width};height:{height};"',
  178. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  179. ' <param name="allowFullScreen" value="true" />\n' +
  180. ' <param name="allowScriptAccess" value="always" />\n' +
  181. ' <param name="autoPlay" value="false" />\n' +
  182. ' <param name="autoStart" value="false" />\n' +
  183. ' <param name="quality" value="high" />\n',
  184. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  185. ' {previewFileIcon}\n' +
  186. ' </div>',
  187. defaultFileActionSettings = {
  188. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  189. removeClass: 'btn btn-xs btn-default',
  190. removeTitle: 'Remove file',
  191. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  192. uploadClass: 'btn btn-xs btn-default',
  193. uploadTitle: 'Upload file',
  194. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  195. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>',
  196. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  197. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  198. indicatorNewTitle: 'Not uploaded yet',
  199. indicatorSuccessTitle: 'Uploaded',
  200. indicatorErrorTitle: 'Upload Error',
  201. indicatorLoadingTitle: 'Uploading ...'
  202. },
  203. tMain1 = '{preview}\n' +
  204. '<div class="kv-upload-progress hide"></div>\n' +
  205. '<div class="input-group {class}">\n' +
  206. ' {caption}\n' +
  207. ' <div class="input-group-btn">\n' +
  208. ' {remove}\n' +
  209. ' {cancel}\n' +
  210. ' {upload}\n' +
  211. ' {browse}\n' +
  212. ' </div>\n' +
  213. '</div>',
  214. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  215. tPreview = '<div class="file-preview {class}">\n' +
  216. ' <div class="close fileinput-remove">&times;</div>\n' +
  217. ' <div class="{dropClass}">\n' +
  218. ' <div class="file-preview-thumbnails">\n' +
  219. ' </div>\n' +
  220. ' <div class="clearfix"></div>' +
  221. ' <div class="file-preview-status text-center text-success"></div>\n' +
  222. ' <div class="kv-fileinput-error"></div>\n' +
  223. ' </div>\n' +
  224. '</div>',
  225. tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  226. tCaption = '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  227. ' <span class="file-caption-ellipsis">&hellip;</span>\n' +
  228. ' <div class="file-caption-name"></div>\n' +
  229. '</div>',
  230. tModal = '<div id="{id}" class="modal fade">\n' +
  231. ' <div class="modal-dialog modal-lg">\n' +
  232. ' <div class="modal-content">\n' +
  233. ' <div class="modal-header">\n' +
  234. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  235. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  236. ' </div>\n' +
  237. ' <div class="modal-body">\n' +
  238. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  239. ' </div>\n' +
  240. ' </div>\n' +
  241. ' </div>\n' +
  242. '</div>',
  243. tProgress = '<div class="progress">\n' +
  244. ' <div class="{class}" role="progressbar"' +
  245. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  246. ' {percent}%\n' +
  247. ' </div>\n' +
  248. '</div>',
  249. tFooter = '<div class="file-thumbnail-footer">\n' +
  250. ' <div class="file-caption-name">{caption}</div>\n' +
  251. ' {actions}\n' +
  252. '</div>',
  253. tActions = '<div class="file-actions">\n' +
  254. ' <div class="file-footer-buttons">\n' +
  255. ' {upload}{delete}{other}' +
  256. ' </div>\n' +
  257. ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
  258. ' <div class="clearfix"></div>\n' +
  259. '</div>',
  260. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  261. 'title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  262. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  263. ' {uploadIcon}\n</button>\n',
  264. tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  265. ' {content}\n' +
  266. ' {footer}\n' +
  267. '</div>\n',
  268. tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  269. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  270. ' ' + DEFAULT_PREVIEW + '\n' +
  271. ' </object>\n' +
  272. ' {footer}\n' +
  273. '</div>',
  274. tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  275. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  276. ' {footer}\n' +
  277. '</div>\n',
  278. tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  279. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  280. ' {data}\n' +
  281. ' </div>\n' +
  282. ' {footer}\n' +
  283. '</div>',
  284. tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  285. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  286. ' <video width="{width}" height="{height}" controls>\n' +
  287. ' <source src="{data}" type="{type}">\n' +
  288. ' ' + DEFAULT_PREVIEW + '\n' +
  289. ' </video>\n' +
  290. ' {footer}\n' +
  291. '</div>\n',
  292. tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  293. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  294. ' <audio controls>\n' +
  295. ' <source src="' + '{data}' + '" type="{type}">\n' +
  296. ' ' + DEFAULT_PREVIEW + '\n' +
  297. ' </audio>\n' +
  298. ' {footer}\n' +
  299. '</div>',
  300. tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  301. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  302. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  303. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  304. ' </object>\n' +
  305. ' {footer}\n' +
  306. '</div>\n',
  307. tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  308. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  309. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  310. ' <param name="movie" value="{caption}" />\n' +
  311. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  312. ' </object>\n' +
  313. ' {footer}\n' +
  314. '</div>',
  315. tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  316. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  317. ' ' + DEFAULT_PREVIEW + '\n' +
  318. ' {footer}\n' +
  319. '</div>',
  320. defaultLayoutTemplates = {
  321. main1: tMain1,
  322. main2: tMain2,
  323. preview: tPreview,
  324. icon: tIcon,
  325. caption: tCaption,
  326. modal: tModal,
  327. progress: tProgress,
  328. footer: tFooter,
  329. actions: tActions,
  330. actionDelete: tActionDelete,
  331. actionUpload: tActionUpload
  332. },
  333. defaultPreviewTemplates = {
  334. generic: tGeneric,
  335. html: tHtml,
  336. image: tImage,
  337. text: tText,
  338. video: tVideo,
  339. audio: tAudio,
  340. flash: tFlash,
  341. object: tObject,
  342. other: tOther
  343. },
  344. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
  345. defaultPreviewSettings = {
  346. image: {width: "auto", height: "160px"},
  347. html: {width: "213px", height: "160px"},
  348. text: {width: "160px", height: "160px"},
  349. video: {width: "213px", height: "160px"},
  350. audio: {width: "213px", height: "80px"},
  351. flash: {width: "213px", height: "160px"},
  352. object: {width: "160px", height: "160px"},
  353. other: {width: "160px", height: "160px"}
  354. },
  355. defaultFileTypeSettings = {
  356. image: function (vType, vName) {
  357. return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  358. },
  359. html: function (vType, vName) {
  360. return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i);
  361. },
  362. text: function (vType, vName) {
  363. return (vType !== undefined && vType.match('text.*')) || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  364. },
  365. video: function (vType, vName) {
  366. return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm)$/i)) || vName.match(/\.(og?|mp4|webm)$/i);
  367. },
  368. audio: function (vType, vName) {
  369. return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  370. },
  371. flash: function (vType, vName) {
  372. return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  373. },
  374. object: function () {
  375. return true;
  376. },
  377. other: function () {
  378. return true;
  379. }
  380. },
  381. isEmpty = function (value, trim) {
  382. return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === '');
  383. },
  384. isArray = function (a) {
  385. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  386. },
  387. isSet = function (needle, haystack) {
  388. return (typeof haystack === 'object' && needle in haystack);
  389. },
  390. getElement = function (options, param, value) {
  391. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  392. },
  393. uniqId = function () {
  394. return Math.round(new Date().getTime() + (Math.random() * 100));
  395. },
  396. htmlEncode = function (str) {
  397. return String(str).repl('&', '&amp;')
  398. .repl('"', '&quot;')
  399. .repl("'", '&#39;')
  400. .repl('<', '&lt;')
  401. .repl('>', '&gt;');
  402. },
  403. replaceTags = function (str, tags) {
  404. var out = str;
  405. $.each(tags, function (key, value) {
  406. if (typeof value === "function") {
  407. value = value();
  408. }
  409. out = out.repl(key, value);
  410. });
  411. return out;
  412. },
  413. objUrl = window.URL || window.webkitURL,
  414. FileInput = function (element, options) {
  415. this.$element = $(element);
  416. if (hasFileAPISupport() || isIE(9)) {
  417. this.init(options);
  418. this.listen();
  419. } else {
  420. this.$element.removeClass('file-loading');
  421. }
  422. };
  423. FileInput.prototype = {
  424. constructor: FileInput,
  425. init: function (options) {
  426. var self = this, $el = self.$element, t;
  427. $.each(options, function (key, value) {
  428. if (key === 'maxFileCount' || key === 'maxFileSize') {
  429. self[key] = getNum(value);
  430. }
  431. self[key] = value;
  432. });
  433. self.fileInputCleared = false;
  434. self.fileBatchCompleted = true;
  435. if (isEmpty(self.allowedPreviewTypes)) {
  436. self.allowedPreviewTypes = defaultPreviewTypes;
  437. }
  438. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  439. self.reader = null;
  440. self.formdata = {};
  441. self.isIE9 = isIE(9);
  442. self.isIE10 = isIE(10);
  443. self.filestack = [];
  444. self.ajaxRequests = [];
  445. self.isError = false;
  446. self.uploadAborted = false;
  447. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  448. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  449. self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl);
  450. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  451. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  452. self.captionTemplate = self.getLayoutTemplate('caption');
  453. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  454. if (isEmpty(self.$element.attr('id'))) {
  455. self.$element.attr('id', uniqId());
  456. }
  457. if (self.$container === undefined) {
  458. self.$container = self.createContainer();
  459. } else {
  460. self.refreshContainer();
  461. }
  462. self.$progress = self.$container.find('.kv-upload-progress');
  463. self.$btnUpload = self.$container.find('.kv-fileinput-upload');
  464. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  465. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  466. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  467. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  468. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  469. self.$errorContainer = getElement(options, 'elErrorContainer',
  470. self.$previewContainer.find('.kv-fileinput-error'));
  471. if (!isEmpty(self.msgErrorClass)) {
  472. addCss(self.$errorContainer, self.msgErrorClass);
  473. }
  474. self.$errorContainer.hide();
  475. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  476. self.previewInitId = "preview-" + uniqId();
  477. self.id = self.$element.attr('id');
  478. previewCache.init(self);
  479. self.initPreview(true);
  480. self.initPreviewDeletes();
  481. self.options = options;
  482. self.setFileDropZoneTitle();
  483. self.uploadCount = 0;
  484. self.uploadPercent = 0;
  485. self.$element.removeClass('file-loading');
  486. t = self.getLayoutTemplate('progress');
  487. self.progressTemplate = t.replace('{class}', self.progressClass);
  488. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  489. self.setEllipsis();
  490. },
  491. parseError: function (jqXHR, errorThrown, fileName) {
  492. var self = this, errMsg = $.trim(errorThrown + ''),
  493. dot = errMsg.slice(-1) === '.' ? '' : '.',
  494. text = '<pre class="text-left">' + $(jqXHR.responseText).text().replace(/\n\s*\n/g, '\n') + '</pre>';
  495. if (self.showAjaxErrorDetails) {
  496. if (errMsg.replace(/\s/g, "X").length > 0) {
  497. errMsg += dot + '<br>' + text;
  498. } else {
  499. errMsg = text;
  500. }
  501. } else {
  502. errMsg += dot;
  503. }
  504. return fileName ? '<b>' + fileName + ': </b>' + jqXHR : errMsg;
  505. },
  506. raise: function (event, params) {
  507. var self = this, e = $.Event(event), out;
  508. if (params !== undefined) {
  509. self.$element.trigger(e, params);
  510. } else {
  511. self.$element.trigger(e);
  512. }
  513. out = e.result || false;
  514. if (!out) {
  515. return;
  516. }
  517. switch (event) {
  518. // ignore these events
  519. case 'filebatchuploadcomplete':
  520. case 'filebatchuploadsuccess':
  521. case 'fileuploaded':
  522. case 'fileclear':
  523. case 'filecleared':
  524. case 'filereset':
  525. case 'fileerror':
  526. case 'filefoldererror':
  527. case 'fileuploaderror':
  528. case 'filebatchuploaderror':
  529. case 'filedeleteerror':
  530. case 'filecustomerror':
  531. break;
  532. // can trigger filecustomerror to abort upload
  533. default:
  534. self.uploadAborted = out;
  535. break;
  536. }
  537. },
  538. getLayoutTemplate: function (t) {
  539. var self = this,
  540. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  541. if (isEmpty(self.customLayoutTags)) {
  542. return template;
  543. }
  544. return replaceTags(template, self.customLayoutTags);
  545. },
  546. getPreviewTemplate: function (t) {
  547. var self = this,
  548. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  549. template = template.repl('{previewFileIcon}', self.previewFileIcon);
  550. if (isEmpty(self.customPreviewTags)) {
  551. return template;
  552. }
  553. return replaceTags(template, self.customPreviewTags);
  554. },
  555. getOutData: function (jqXHR, responseData, filesData) {
  556. var self = this;
  557. jqXHR = jqXHR || {};
  558. responseData = responseData || {};
  559. filesData = filesData || self.filestack.slice(0) || {};
  560. return {
  561. form: self.formdata,
  562. files: filesData,
  563. extra: self.getExtraData(),
  564. response: responseData,
  565. reader: self.reader,
  566. jqXHR: jqXHR
  567. };
  568. },
  569. setEllipsis: function () {
  570. var self = this, $capCont = self.$captionContainer, $cap = self.$caption,
  571. $div = $cap.clone().css('height', 'auto').hide();
  572. $capCont.parent().before($div);
  573. $capCont.removeClass('kv-has-ellipsis');
  574. if ($div.outerWidth() > $cap.outerWidth()) {
  575. $capCont.addClass('kv-has-ellipsis');
  576. }
  577. $div.remove();
  578. },
  579. listen: function () {
  580. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile,
  581. $form = $el.closest('form');
  582. $el.on('change', $.proxy(self.change, self));
  583. $(window).on('resize', function () {
  584. self.setEllipsis();
  585. });
  586. $btnFile.off('click').on('click', function () {
  587. self.raise('filebrowse');
  588. if (self.isError && !self.isUploadable) {
  589. self.clear();
  590. }
  591. $cap.focus();
  592. });
  593. $form.off('reset').on('reset', $.proxy(self.reset, self));
  594. self.$container.off('click')
  595. .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self))
  596. .on('click', '.fileinput-cancel', $.proxy(self.cancel, self));
  597. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  598. self.initDragDrop();
  599. }
  600. if (!self.isUploadable) {
  601. $form.on('submit', $.proxy(self.submitForm, self));
  602. }
  603. self.$container.find('.kv-fileinput-upload').off('click').on('click', function (e) {
  604. if (!self.isUploadable) {
  605. return;
  606. }
  607. e.preventDefault();
  608. if (!$(this).hasClass('disabled') && isEmpty($(this).attr('disabled'))) {
  609. self.upload();
  610. }
  611. });
  612. },
  613. submitForm: function () {
  614. var self = this, $el = self.$element, files = $el.get(0).files;
  615. if (files && files.length < self.minFileCount && self.minFileCount > 0) {
  616. self.noFilesError({});
  617. return false;
  618. }
  619. return !self.abort({});
  620. },
  621. abort: function (params) {
  622. var self = this, data;
  623. if (self.uploadAborted && typeof self.uploadAborted === "object" && self.uploadAborted.message !== undefined) {
  624. if (self.uploadAborted.data !== undefined) {
  625. data = self.getOutData({}, self.uploadAborted.data);
  626. } else {
  627. data = self.getOutData();
  628. }
  629. data = $.extend(data, params);
  630. self.showUploadError(self.uploadAborted.message, data, 'filecustomerror');
  631. return true;
  632. }
  633. return false;
  634. },
  635. noFilesError: function (params) {
  636. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  637. msg = self.msgFilesTooLess.repl('{n}', self.minFileCount).repl('{files}', label),
  638. $error = self.$errorContainer;
  639. $error.html(msg);
  640. self.isError = true;
  641. self.updateFileDetails(0);
  642. $error.fadeIn(800);
  643. self.raise('fileerror', [params]);
  644. self.clearFileInput();
  645. addCss(self.$container, 'has-error');
  646. },
  647. setProgress: function (p) {
  648. var self = this, pct = Math.min(p, 100),
  649. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  650. self.$progress.html(template.repl('{percent}', pct));
  651. },
  652. upload: function () {
  653. var self = this, totLen = self.getFileStack().length, params = {},
  654. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  655. if (totLen < self.minFileCount && self.minFileCount > 0) {
  656. self.noFilesError(params);
  657. return;
  658. }
  659. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  660. return;
  661. }
  662. self.resetUpload();
  663. self.$progress.removeClass('hide');
  664. self.uploadCount = 0;
  665. self.uploadPercent = 0;
  666. self.lock();
  667. self.setProgress(0);
  668. if (totLen === 0 && hasExtraData) {
  669. self.uploadExtraOnly();
  670. return;
  671. }
  672. len = self.filestack.length;
  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') {
  1161. return;
  1162. }
  1163. if (out.initialPreview !== undefined) {
  1164. content = out.initialPreview || [];
  1165. config = out.initialPreviewConfig || [];
  1166. append = out.append === undefined || out.append ? true : false;
  1167. self.overwriteInitial = false;
  1168. if ($thumb !== undefined && !!allFiles) {
  1169. index = previewCache.add(self.id, content, config[0], append);
  1170. data = previewCache.get(self.id, index, false);
  1171. $newThumb = $(data).hide();
  1172. $thumb.after($newThumb).fadeOut('slow', function () {
  1173. $newThumb.fadeIn('slow').css('display:inline-block');
  1174. self.initPreviewDeletes();
  1175. });
  1176. } else {
  1177. if (allFiles) {
  1178. self.uploadCache.content.push(content[0]);
  1179. self.uploadCache.config.push(config[0]);
  1180. self.uploadCache.append = append;
  1181. } else {
  1182. previewCache.set(self.id, content, config, append);
  1183. self.initPreview();
  1184. self.initPreviewDeletes();
  1185. }
  1186. }
  1187. }
  1188. },
  1189. uploadSingle: function (i, files, allFiles) {
  1190. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1191. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1192. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1193. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  1194. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1195. setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError,
  1196. params = {id: previewId, index: i};
  1197. self.formdata = formdata;
  1198. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1199. return;
  1200. }
  1201. chkComplete = function () {
  1202. var $thumbs = self.$preview.find(PREVIEW_FRAMES + '.file-uploading');
  1203. if ($thumbs.length > 0 && self.fileBatchCompleted) {
  1204. return;
  1205. }
  1206. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.append);
  1207. self.initPreview();
  1208. self.initPreviewDeletes();
  1209. self.setProgress(100);
  1210. self.unlock();
  1211. self.clearFileInput();
  1212. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1213. self.fileBatchCompleted = true;
  1214. };
  1215. setIndicator = function (icon, msg) {
  1216. $indicator.html(config[icon]);
  1217. $indicator.attr('title', config[msg]);
  1218. };
  1219. updateProgress = function () {
  1220. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1221. return;
  1222. }
  1223. self.uploadCount += 1;
  1224. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1225. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1226. self.setProgress(self.uploadPercent);
  1227. self.initPreviewDeletes();
  1228. };
  1229. resetActions = function () {
  1230. $btnUpload.removeAttr('disabled');
  1231. $btnDelete.removeAttr('disabled');
  1232. $thumb.removeClass('file-uploading');
  1233. };
  1234. fnBefore = function (jqXHR) {
  1235. outData = self.getOutData(jqXHR);
  1236. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  1237. addCss($thumb, 'file-uploading');
  1238. $btnUpload.attr('disabled', true);
  1239. $btnDelete.attr('disabled', true);
  1240. if (!allFiles) {
  1241. self.lock();
  1242. }
  1243. self.raise('filepreupload', [outData, previewId, i]);
  1244. params = $.extend(params, outData);
  1245. if (self.abort(params)) {
  1246. jqXHR.abort();
  1247. self.setProgress(100);
  1248. }
  1249. };
  1250. fnSuccess = function (data, textStatus, jqXHR) {
  1251. outData = self.getOutData(jqXHR, data);
  1252. params = $.extend(params, outData);
  1253. setTimeout(function () {
  1254. if (data.error === undefined) {
  1255. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  1256. $btnUpload.hide();
  1257. $btnDelete.hide();
  1258. self.filestack[i] = undefined;
  1259. self.raise('fileuploaded', [outData, previewId, i]);
  1260. self.initUploadSuccess(data, $thumb, allFiles);
  1261. if (!allFiles) {
  1262. self.resetFileStack();
  1263. }
  1264. } else {
  1265. setIndicator('indicatorError', 'indicatorErrorTitle');
  1266. self.showUploadError(data.error, params);
  1267. }
  1268. }, 100);
  1269. };
  1270. fnComplete = function () {
  1271. setTimeout(function () {
  1272. updateProgress();
  1273. resetActions();
  1274. if (!allFiles) {
  1275. self.unlock(false);
  1276. } else {
  1277. setTimeout(function () {
  1278. chkComplete();
  1279. }, 500);
  1280. }
  1281. }, 100);
  1282. };
  1283. fnError = function (jqXHR, textStatus, errorThrown) {
  1284. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1285. setIndicator('indicatorError', 'indicatorErrorTitle');
  1286. params = $.extend(params, self.getOutData(jqXHR));
  1287. self.showUploadError(errMsg, params);
  1288. };
  1289. formdata.append(self.uploadFileAttr, files[i]);
  1290. formdata.append('file_id', i);
  1291. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1292. },
  1293. uploadBatch: function () {
  1294. var self = this, files = self.filestack, total = files.length, config,
  1295. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1296. setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1297. params = {};
  1298. self.formdata = new FormData();
  1299. if (total === 0 || !hasPostData || self.abort(params)) {
  1300. return;
  1301. }
  1302. config = self.fileActionSettings;
  1303. setIndicator = function (i, icon, msg) {
  1304. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1305. $indicator.html(config[icon]);
  1306. $indicator.attr('title', config[msg]);
  1307. };
  1308. enableActions = function (i) {
  1309. var $thumb = $('#' + self.previewInitId + "-" + i + ':not(.file-preview-initial)'),
  1310. $btnUpload = $thumb.find('.kv-file-upload'),
  1311. $btnDelete = $thumb.find('.kv-file-delete');
  1312. $thumb.removeClass('file-uploading');
  1313. $btnUpload.removeAttr('disabled');
  1314. $btnDelete.removeAttr('disabled');
  1315. };
  1316. setAllUploaded = function () {
  1317. $.each(files, function (key, data) {
  1318. self.filestack[key] = undefined;
  1319. });
  1320. self.clearFileInput();
  1321. };
  1322. fnBefore = function (jqXHR) {
  1323. self.lock();
  1324. var outData = self.getOutData(jqXHR);
  1325. if (self.showPreview) {
  1326. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1327. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1328. addCss($thumb, 'file-uploading');
  1329. $btnUpload.attr('disabled', true);
  1330. $btnDelete.attr('disabled', true);
  1331. });
  1332. }
  1333. self.raise('filebatchpreupload', [outData]);
  1334. if (self.abort(outData)) {
  1335. jqXHR.abort();
  1336. }
  1337. };
  1338. fnSuccess = function (data, textStatus, jqXHR) {
  1339. var outData = self.getOutData(jqXHR, data),
  1340. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1341. if (data.error === undefined || isEmpty(data.error)) {
  1342. self.raise('filebatchuploadsuccess', [outData]);
  1343. setAllUploaded();
  1344. if (self.showPreview) {
  1345. self.$preview.find('.kv-file-upload').hide();
  1346. self.$preview.find('.kv-file-remove').hide();
  1347. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1348. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1349. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1350. enableActions(key);
  1351. });
  1352. self.initUploadSuccess(data);
  1353. } else {
  1354. self.reset();
  1355. }
  1356. } else {
  1357. if (self.showPreview) {
  1358. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1359. var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10);
  1360. enableActions(key);
  1361. if (keys.length === 0) {
  1362. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1363. return;
  1364. }
  1365. if ($.inArray(key, keys) !== -1) {
  1366. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1367. } else {
  1368. $thumb.find('.kv-file-upload').hide();
  1369. $thumb.find('.kv-file-remove').hide();
  1370. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1371. self.filestack[key] = undefined;
  1372. }
  1373. });
  1374. self.initUploadSuccess(data);
  1375. }
  1376. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1377. }
  1378. };
  1379. fnComplete = function () {
  1380. self.setProgress(100);
  1381. self.unlock();
  1382. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1383. self.clearFileInput();
  1384. };
  1385. fnError = function (jqXHR, textStatus, errorThrown) {
  1386. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1387. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1388. self.uploadFileCount = total - 1;
  1389. if (!self.showPreview) {
  1390. return;
  1391. }
  1392. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1393. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1394. $thumb.removeClass('file-uploading');
  1395. if (self.filestack[key] !== undefined) {
  1396. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1397. }
  1398. });
  1399. self.$preview.find(PREVIEW_FRAMES).removeClass('file-uploading');
  1400. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-upload').removeAttr('disabled');
  1401. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-delete').removeAttr('disabled');
  1402. };
  1403. $.each(files, function (key, data) {
  1404. if (!isEmpty(files[key])) {
  1405. self.formdata.append(self.uploadFileAttr, data);
  1406. }
  1407. });
  1408. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1409. },
  1410. uploadExtraOnly: function () {
  1411. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1412. self.formdata = new FormData();
  1413. if (self.abort(params)) {
  1414. return;
  1415. }
  1416. fnBefore = function (jqXHR) {
  1417. self.lock();
  1418. var outData = self.getOutData(jqXHR);
  1419. self.raise('filebatchpreupload', [outData]);
  1420. self.setProgress(50);
  1421. params.data = outData;
  1422. params.xhr = jqXHR;
  1423. if (self.abort(params)) {
  1424. jqXHR.abort();
  1425. self.setProgress(100);
  1426. }
  1427. };
  1428. fnSuccess = function (data, textStatus, jqXHR) {
  1429. var outData = self.getOutData(jqXHR, data);
  1430. if (data.error === undefined || isEmpty(data.error)) {
  1431. self.raise('filebatchuploadsuccess', [outData]);
  1432. self.clearFileInput();
  1433. self.initUploadSuccess(data);
  1434. } else {
  1435. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1436. }
  1437. };
  1438. fnComplete = function () {
  1439. self.setProgress(100);
  1440. self.unlock();
  1441. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1442. self.clearFileInput();
  1443. };
  1444. fnError = function (jqXHR, textStatus, errorThrown) {
  1445. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1446. params.data = outData;
  1447. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1448. };
  1449. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1450. },
  1451. hideFileIcon: function () {
  1452. if (this.overwriteInitial) {
  1453. this.$captionContainer.find('.kv-caption-icon').hide();
  1454. }
  1455. },
  1456. showFileIcon: function () {
  1457. this.$captionContainer.find('.kv-caption-icon').show();
  1458. },
  1459. resetErrors: function (fade) {
  1460. var self = this, $error = self.$errorContainer;
  1461. self.isError = false;
  1462. self.$container.removeClass('has-error');
  1463. $error.html('');
  1464. if (fade) {
  1465. $error.fadeOut('slow');
  1466. } else {
  1467. $error.hide();
  1468. }
  1469. },
  1470. showFolderError: function (folders) {
  1471. var self = this, $error = self.$errorContainer;
  1472. if (!folders) {
  1473. return;
  1474. }
  1475. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1476. $error.fadeIn(800);
  1477. addCss(self.$container, 'has-error');
  1478. self.raise('filefoldererror', [folders]);
  1479. },
  1480. showUploadError: function (msg, params, event) {
  1481. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1482. if ($error.find('ul').length === 0) {
  1483. $error.html('<ul class="text-left"><br><li>' + msg + '</li></ul>');
  1484. } else {
  1485. $error.find('ul').append('<br><li>' + msg + '</li>');
  1486. }
  1487. $error.fadeIn(800);
  1488. self.raise(ev, [params]);
  1489. addCss(self.$container, 'has-error');
  1490. return true;
  1491. },
  1492. showError: function (msg, params, event) {
  1493. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1494. params = params || {};
  1495. params.reader = self.reader;
  1496. $error.html(msg);
  1497. $error.fadeIn(800);
  1498. self.raise(ev, [params]);
  1499. if (!self.isUploadable) {
  1500. self.clearFileInput();
  1501. }
  1502. addCss(self.$container, 'has-error');
  1503. self.$btnUpload.attr('disabled', true);
  1504. return true;
  1505. },
  1506. errorHandler: function (evt, caption) {
  1507. var self = this, err = evt.target.error;
  1508. switch (err.code) {
  1509. case err.NOT_FOUND_ERR:
  1510. self.showError(self.msgFileNotFound.repl('{name}', caption));
  1511. break;
  1512. case err.SECURITY_ERR:
  1513. self.showError(self.msgFileSecured.repl('{name}', caption));
  1514. break;
  1515. case err.NOT_READABLE_ERR:
  1516. self.showError(self.msgFileNotReadable.repl('{name}', caption));
  1517. break;
  1518. case err.ABORT_ERR:
  1519. self.showError(self.msgFilePreviewAborted.repl('{name}', caption));
  1520. break;
  1521. default:
  1522. self.showError(self.msgFilePreviewError.repl('{name}', caption));
  1523. }
  1524. },
  1525. parseFileType: function (file) {
  1526. var self = this, isValid, vType, cat, i;
  1527. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1528. cat = defaultPreviewTypes[i];
  1529. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1530. vType = isValid(file.type, file.name) ? cat : '';
  1531. if (!isEmpty(vType)) {
  1532. return vType;
  1533. }
  1534. }
  1535. return 'other';
  1536. },
  1537. previewDefault: function (file, previewId, isDisabled) {
  1538. if (!this.showPreview) {
  1539. return;
  1540. }
  1541. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1542. config = self.previewSettings.other,
  1543. footer = self.renderFileFooter(file.name, config.width),
  1544. previewOtherTemplate = self.getPreviewTemplate('other'),
  1545. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1546. frameClass = '';
  1547. if (isDisabled === true) {
  1548. frameClass = ' btn disabled';
  1549. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1550. }
  1551. self.$preview.append("\n" + previewOtherTemplate
  1552. .repl('{previewId}', previewId)
  1553. .repl('{frameClass}', frameClass)
  1554. .repl('{fileindex}', ind)
  1555. .repl('{caption}', self.slug(file.name))
  1556. .repl('{width}', config.width)
  1557. .repl('{height}', config.height)
  1558. .repl('{type}', file.type)
  1559. .repl('{data}', data)
  1560. .repl('{footer}', footer));
  1561. $obj.on('load', function () {
  1562. objUrl.revokeObjectURL($obj.attr('data'));
  1563. });
  1564. },
  1565. previewFile: function (file, theFile, previewId, data) {
  1566. if (!this.showPreview) {
  1567. return;
  1568. }
  1569. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1570. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1571. tmplt = self.getPreviewTemplate(cat),
  1572. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1573. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1574. chkTypes = types.indexOf(cat) >= 0, id, height,
  1575. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1576. footer = self.renderFileFooter(caption, config.width), modal = '',
  1577. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1578. if (chkTypes && chkMimes) {
  1579. if (cat === 'text') {
  1580. strText = htmlEncode(theFile.target.result);
  1581. objUrl.revokeObjectURL(data);
  1582. if (strText.length > wrapLen) {
  1583. id = 'text-' + uniqId();
  1584. height = window.innerHeight * 0.75;
  1585. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1586. .repl('{title}', caption)
  1587. .repl('{height}', height)
  1588. .repl('{body}', strText);
  1589. wrapInd = wrapInd
  1590. .repl('{title}', caption)
  1591. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1592. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1593. }
  1594. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1595. .repl('{frameClass}', '')
  1596. .repl('{type}', file.type).repl('{width}', config.width)
  1597. .repl('{height}', config.height).repl('{data}', strText)
  1598. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1599. } else {
  1600. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1601. .repl('{frameClass}', '')
  1602. .repl('{type}', file.type).repl('{data}', data)
  1603. .repl('{width}', config.width).repl('{height}', config.height)
  1604. .repl('{footer}', footer).repl('{fileindex}', ind);
  1605. }
  1606. self.$preview.append("\n" + content);
  1607. self.autoSizeImage(previewId);
  1608. } else {
  1609. self.previewDefault(file, previewId);
  1610. }
  1611. },
  1612. slugDefault: function (text) {
  1613. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\-.\\\/ ]+/g, '');
  1614. },
  1615. getFileStack: function () {
  1616. var self = this;
  1617. return self.filestack.filter(function (n) {
  1618. return n !== undefined;
  1619. });
  1620. },
  1621. readFiles: function (files) {
  1622. this.reader = new FileReader();
  1623. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1624. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1625. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1626. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1627. throwError = function (msg, file, previewId, index) {
  1628. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1629. p2 = {id: previewId, index: index, file: file, files: files};
  1630. self.previewDefault(file, previewId, true);
  1631. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1632. };
  1633. function readFile(i) {
  1634. if (isEmpty($el.attr('multiple'))) {
  1635. numFiles = 1;
  1636. }
  1637. if (i >= numFiles) {
  1638. $container.removeClass('loading');
  1639. $status.html('');
  1640. return;
  1641. }
  1642. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1643. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1644. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1645. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1646. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1647. if (!isEmpty(fileExt)) {
  1648. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1649. }
  1650. fileSize = fileSize.toFixed(2);
  1651. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1652. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1653. .repl('{size}', fileSize)
  1654. .repl('{maxSize}', self.maxFileSize);
  1655. self.isError = throwError(msg, file, previewId, i);
  1656. return;
  1657. }
  1658. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1659. for (j = 0; j < fileTypes.length; j += 1) {
  1660. typ = fileTypes[j];
  1661. checkFile = settings[typ];
  1662. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1663. fileCount += isEmpty(chk) ? 0 : chk.length;
  1664. }
  1665. if (fileCount === 0) {
  1666. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1667. self.isError = throwError(msg, file, previewId, i);
  1668. return;
  1669. }
  1670. }
  1671. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1672. chk = caption.match(fileExtExpr);
  1673. fileCount += isEmpty(chk) ? 0 : chk.length;
  1674. if (fileCount === 0) {
  1675. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1676. strExt);
  1677. self.isError = throwError(msg, file, previewId, i);
  1678. return;
  1679. }
  1680. }
  1681. if (!self.showPreview) {
  1682. self.filestack.push(file);
  1683. setTimeout(readFile(i + 1), 100);
  1684. self.raise('fileloaded', [file, previewId, i, reader]);
  1685. return;
  1686. }
  1687. if ($preview.length > 0 && FileReader !== undefined) {
  1688. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1689. $container.addClass('loading');
  1690. reader.onerror = function (evt) {
  1691. self.errorHandler(evt, caption);
  1692. };
  1693. reader.onload = function (theFile) {
  1694. self.previewFile(file, theFile, previewId, previewData);
  1695. self.initFileActions();
  1696. };
  1697. reader.onloadend = function () {
  1698. msg = msgProgress
  1699. .repl('{index}', i + 1).repl('{files}', numFiles)
  1700. .repl('{percent}', 50).repl('{name}', caption);
  1701. setTimeout(function () {
  1702. $status.html(msg);
  1703. objUrl.revokeObjectURL(previewData);
  1704. }, 100);
  1705. setTimeout(function () {
  1706. readFile(i + 1);
  1707. self.updateFileDetails(numFiles);
  1708. }, 100);
  1709. self.raise('fileloaded', [file, previewId, i, reader]);
  1710. };
  1711. reader.onprogress = function (data) {
  1712. if (data.lengthComputable) {
  1713. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1714. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1715. .repl('{percent}', progress).repl('{name}', caption);
  1716. setTimeout(function () {
  1717. $status.html(msg);
  1718. }, 100);
  1719. }
  1720. };
  1721. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1722. if (isText(file.type, caption)) {
  1723. reader.readAsText(file, self.textEncoding);
  1724. } else {
  1725. reader.readAsArrayBuffer(file);
  1726. }
  1727. } else {
  1728. self.previewDefault(file, previewId);
  1729. setTimeout(function () {
  1730. readFile(i + 1);
  1731. self.updateFileDetails(numFiles);
  1732. }, 100);
  1733. self.raise('fileloaded', [file, previewId, i, reader]);
  1734. }
  1735. self.filestack.push(file);
  1736. }
  1737. readFile(0);
  1738. self.updateFileDetails(numFiles, false);
  1739. },
  1740. updateFileDetails: function (numFiles) {
  1741. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1742. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1743. n = self.isUploadable ? fileStack.length : numFiles,
  1744. nFiles = previewCache.count(self.id) + n,
  1745. log = n > 1 ? msgSelected.repl('{n}', nFiles) : label;
  1746. if (self.isError) {
  1747. self.$previewContainer.removeClass('loading');
  1748. self.$previewStatus.html('');
  1749. self.$captionContainer.find('.kv-caption-icon').hide();
  1750. } else {
  1751. self.showFileIcon();
  1752. }
  1753. self.setCaption(log, self.isError);
  1754. self.$container.removeClass('file-input-new file-input-ajax-new');
  1755. if (arguments.length === 1) {
  1756. self.raise('fileselect', [numFiles, label]);
  1757. }
  1758. if (previewCache.count(self.id)) {
  1759. self.initPreviewDeletes();
  1760. }
  1761. },
  1762. change: function (e) {
  1763. var self = this, $el = self.$element;
  1764. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1765. self.fileInputCleared = false;
  1766. return;
  1767. }
  1768. self.fileInputCleared = false;
  1769. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1770. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1771. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1772. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr !== 0),
  1773. throwError = function (mesg, file, previewId, index) {
  1774. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1775. p2 = {id: previewId, index: index, file: file, files: files};
  1776. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1777. };
  1778. self.resetUpload();
  1779. self.hideFileIcon();
  1780. if (self.isUploadable) {
  1781. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1782. }
  1783. if (isDragDrop) {
  1784. tfiles = [];
  1785. while (files[i]) {
  1786. f = files[i];
  1787. if (!f.type && f.size % 4096 === 0) {
  1788. folders++;
  1789. } else {
  1790. tfiles.push(f);
  1791. }
  1792. i++;
  1793. }
  1794. } else {
  1795. if (e.target.files === undefined) {
  1796. tfiles = e.target && e.target.value ? [
  1797. {name: e.target.value.replace(/^.+\\/, '')}
  1798. ] : [];
  1799. } else {
  1800. tfiles = e.target.files;
  1801. }
  1802. }
  1803. if (isEmpty(tfiles) || tfiles.length === 0) {
  1804. if (!isAjaxUpload) {
  1805. self.clear();
  1806. }
  1807. self.showFolderError(folders);
  1808. self.raise('fileselectnone');
  1809. return;
  1810. }
  1811. self.resetErrors();
  1812. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1813. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1814. var out = previewCache.out(self.id);
  1815. $preview.html(out.content);
  1816. self.setCaption(out.caption);
  1817. self.initPreviewDeletes();
  1818. } else {
  1819. $preview.html('');
  1820. }
  1821. if (isSingleUpload && ctr > 0) {
  1822. self.filestack = [];
  1823. }
  1824. }
  1825. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1826. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1827. msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total);
  1828. self.isError = throwError(msg, null, null, null);
  1829. self.$captionContainer.find('.kv-caption-icon').hide();
  1830. self.$caption.html(self.msgValidationError);
  1831. self.setEllipsis();
  1832. self.$container.removeClass('file-input-new file-input-ajax-new');
  1833. return;
  1834. }
  1835. if (!self.isIE9) {
  1836. self.readFiles(tfiles);
  1837. } else {
  1838. self.updateFileDetails(1);
  1839. }
  1840. self.showFolderError(folders);
  1841. if (isAjaxUpload) {
  1842. self.raise('filebatchselected', [self.getFileStack()]);
  1843. } else {
  1844. self.raise('filebatchselected', [tfiles]);
  1845. }
  1846. self.reader = null;
  1847. },
  1848. autoSizeImage: function (previewId) {
  1849. var self = this, $preview = self.$preview,
  1850. $thumb = $preview.find("#" + previewId),
  1851. $img = $thumb.find('img'), w1, w2, $cap;
  1852. if (!$img.length) {
  1853. return;
  1854. }
  1855. $img.on('load', function () {
  1856. w1 = $thumb.width();
  1857. w2 = $preview.width();
  1858. if (w1 > w2) {
  1859. $img.css('width', '100%');
  1860. $thumb.css('width', '97%');
  1861. }
  1862. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1863. if ($cap.length) {
  1864. $cap.width($img.width());
  1865. $cap.attr('title', $cap.text());
  1866. }
  1867. self.raise('fileimageloaded', previewId);
  1868. });
  1869. },
  1870. setCaption: function (content, isError) {
  1871. var self = this, err = isError || false, title, out;
  1872. if (isEmpty(content) || self.$caption.length === 0) {
  1873. return;
  1874. }
  1875. if (err) {
  1876. title = $('<div>' + self.msgValidationError + '</div>').text();
  1877. out = '<span class="' + self.msgValidationErrorClass + '">' +
  1878. self.msgValidationErrorIcon + title + '</span>';
  1879. } else {
  1880. title = $('<div>' + content + '</div>').text();
  1881. out = title + self.getLayoutTemplate('icon');
  1882. }
  1883. self.$caption.html(out);
  1884. self.$caption.attr('title', title);
  1885. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1886. self.setEllipsis();
  1887. },
  1888. initBrowse: function ($container) {
  1889. var self = this;
  1890. self.$btnFile = $container.find('.btn-file');
  1891. self.$btnFile.append(self.$element);
  1892. },
  1893. createContainer: function () {
  1894. var self = this,
  1895. $container = $(document.createElement("span"))
  1896. .attr({"class": 'file-input file-input-new'})
  1897. .html(self.renderMain());
  1898. self.$element.before($container);
  1899. self.initBrowse($container);
  1900. return $container;
  1901. },
  1902. refreshContainer: function () {
  1903. var self = this, $container = self.$container;
  1904. $container.before(self.$element);
  1905. $container.html(self.renderMain());
  1906. self.initBrowse($container);
  1907. },
  1908. renderMain: function () {
  1909. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  1910. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  1911. .repl('{dropClass}', dropCss) : '',
  1912. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  1913. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  1914. return self.mainTemplate.repl('{class}', self.mainClass)
  1915. .repl('{preview}', preview)
  1916. .repl('{caption}', caption)
  1917. .repl('{upload}', self.renderUpload())
  1918. .repl('{remove}', self.renderRemove())
  1919. .repl('{cancel}', self.renderCancel())
  1920. .repl('{browse}', self.renderBrowse());
  1921. },
  1922. renderBrowse: function () {
  1923. var self = this, css = self.browseClass + ' btn-file', status = '';
  1924. if (self.isDisabled) {
  1925. status = ' disabled ';
  1926. }
  1927. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1928. },
  1929. renderRemove: function () {
  1930. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1931. if (!self.showRemove) {
  1932. return '';
  1933. }
  1934. if (self.isDisabled) {
  1935. status = ' disabled ';
  1936. }
  1937. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1938. },
  1939. renderCancel: function () {
  1940. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  1941. if (!self.showCancel) {
  1942. return '';
  1943. }
  1944. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1945. },
  1946. renderUpload: function () {
  1947. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1948. if (!self.showUpload) {
  1949. return '';
  1950. }
  1951. if (self.isDisabled) {
  1952. status = ' disabled ';
  1953. }
  1954. if (!self.isUploadable || self.isDisabled) {
  1955. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1956. } else {
  1957. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1958. }
  1959. return content;
  1960. }
  1961. };
  1962. //FileInput plugin definition
  1963. $.fn.fileinput = function (option) {
  1964. if (!hasFileAPISupport() && !isIE(9)) {
  1965. return;
  1966. }
  1967. var args = Array.apply(null, arguments);
  1968. args.shift();
  1969. return this.each(function () {
  1970. var $this = $(this),
  1971. data = $this.data('fileinput'),
  1972. options = typeof option === 'object' && option;
  1973. if (!data) {
  1974. data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()));
  1975. $this.data('fileinput', data);
  1976. }
  1977. if (typeof option === 'string') {
  1978. data[option].apply(data, args);
  1979. }
  1980. });
  1981. };
  1982. $.fn.fileinput.defaults = {
  1983. showCaption: true,
  1984. showPreview: true,
  1985. showRemove: true,
  1986. showUpload: true,
  1987. showCancel: true,
  1988. mainClass: '',
  1989. previewClass: '',
  1990. captionClass: '',
  1991. mainTemplate: null,
  1992. initialCaption: '',
  1993. initialPreview: [],
  1994. initialPreviewDelimiter: '*$$*',
  1995. initialPreviewConfig: [],
  1996. initialPreviewShowDelete: true,
  1997. deleteUrl: '',
  1998. deleteExtraData: {},
  1999. overwriteInitial: true,
  2000. layoutTemplates: defaultLayoutTemplates,
  2001. previewTemplates: defaultPreviewTemplates,
  2002. allowedPreviewTypes: defaultPreviewTypes,
  2003. allowedPreviewMimeTypes: null,
  2004. allowedFileTypes: null,
  2005. allowedFileExtensions: null,
  2006. customLayoutTags: {},
  2007. customPreviewTags: {},
  2008. previewSettings: defaultPreviewSettings,
  2009. fileTypeSettings: defaultFileTypeSettings,
  2010. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2011. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2012. browseClass: 'btn btn-primary',
  2013. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2014. removeClass: 'btn btn-default',
  2015. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2016. cancelClass: 'btn btn-default',
  2017. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2018. uploadClass: 'btn btn-default',
  2019. uploadUrl: null,
  2020. uploadAsync: true,
  2021. uploadExtraData: {},
  2022. maxFileSize: 0,
  2023. minFileCount: 0,
  2024. maxFileCount: 0,
  2025. msgValidationErrorClass: 'text-danger',
  2026. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2027. msgErrorClass: 'file-error-message',
  2028. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2029. progressCompleteClass: "progress-bar progress-bar-success",
  2030. previewFileType: 'image',
  2031. wrapTextLength: 250,
  2032. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2033. elCaptionContainer: null,
  2034. elCaptionText: null,
  2035. elPreviewContainer: null,
  2036. elPreviewImage: null,
  2037. elPreviewStatus: null,
  2038. elErrorContainer: null,
  2039. slugCallback: null,
  2040. dropZoneEnabled: true,
  2041. dropZoneTitleClass: 'file-drop-zone-title',
  2042. fileActionSettings: {},
  2043. otherActionButtons: '',
  2044. textEncoding: 'UTF-8',
  2045. ajaxSettings: {},
  2046. ajaxDeleteSettings: {},
  2047. showAjaxErrorDetails: true
  2048. };
  2049. $.fn.fileinput.locales = {};
  2050. $.fn.fileinput.locales.en = {
  2051. fileSingle: 'file',
  2052. filePlural: 'files',
  2053. browseLabel: 'Browse &hellip;',
  2054. removeLabel: 'Remove',
  2055. removeTitle: 'Clear selected files',
  2056. cancelLabel: 'Cancel',
  2057. cancelTitle: 'Abort ongoing upload',
  2058. uploadLabel: 'Upload',
  2059. uploadTitle: 'Upload selected files',
  2060. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2061. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2062. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2063. msgFileNotFound: 'File "{name}" not found!',
  2064. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2065. msgFileNotReadable: 'File "{name}" is not readable.',
  2066. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2067. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2068. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2069. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2070. msgValidationError: 'File Upload Error',
  2071. msgLoading: 'Loading file {index} of {files} &hellip;',
  2072. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2073. msgSelected: '{n} files selected',
  2074. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2075. dropZoneTitle: 'Drag & drop files here &hellip;'
  2076. };
  2077. $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.en);
  2078. $.fn.fileinput.Constructor = FileInput;
  2079. /**
  2080. * Convert automatically file inputs with class 'file'
  2081. * into a bootstrap fileinput control.
  2082. */
  2083. $(document).ready(function () {
  2084. var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0;
  2085. if (count > 0) {
  2086. $input.fileinput();
  2087. }
  2088. });
  2089. })(window.jQuery);