fileinput.js 95 KB

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