fileinput.js 95 KB

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