ng-file-upload-all.js 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898
  1. /**!
  2. * AngularJS file upload directives and services. Supports: file upload/drop/paste, resume, cancel/abort,
  3. * progress, resize, thumbnail, preview, validation and CORS
  4. * FileAPI Flash shim for old browsers not supporting FormData
  5. * @author Danial <danial.farid@gmail.com>
  6. * @version 12.2.13
  7. */
  8. (function () {
  9. /** @namespace FileAPI.noContentTimeout */
  10. function patchXHR(fnName, newFn) {
  11. window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]);
  12. }
  13. function redefineProp(xhr, prop, fn) {
  14. try {
  15. Object.defineProperty(xhr, prop, {get: fn});
  16. } catch (e) {/*ignore*/
  17. }
  18. }
  19. if (!window.FileAPI) {
  20. window.FileAPI = {};
  21. }
  22. if (!window.XMLHttpRequest) {
  23. throw 'AJAX is not supported. XMLHttpRequest is not defined.';
  24. }
  25. FileAPI.shouldLoad = !window.FormData || FileAPI.forceLoad;
  26. if (FileAPI.shouldLoad) {
  27. var initializeUploadListener = function (xhr) {
  28. if (!xhr.__listeners) {
  29. if (!xhr.upload) xhr.upload = {};
  30. xhr.__listeners = [];
  31. var origAddEventListener = xhr.upload.addEventListener;
  32. xhr.upload.addEventListener = function (t, fn) {
  33. xhr.__listeners[t] = fn;
  34. if (origAddEventListener) origAddEventListener.apply(this, arguments);
  35. };
  36. }
  37. };
  38. patchXHR('open', function (orig) {
  39. return function (m, url, b) {
  40. initializeUploadListener(this);
  41. this.__url = url;
  42. try {
  43. orig.apply(this, [m, url, b]);
  44. } catch (e) {
  45. if (e.message.indexOf('Access is denied') > -1) {
  46. this.__origError = e;
  47. orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]);
  48. }
  49. }
  50. };
  51. });
  52. patchXHR('getResponseHeader', function (orig) {
  53. return function (h) {
  54. return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h]));
  55. };
  56. });
  57. patchXHR('getAllResponseHeaders', function (orig) {
  58. return function () {
  59. return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this));
  60. };
  61. });
  62. patchXHR('abort', function (orig) {
  63. return function () {
  64. return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this));
  65. };
  66. });
  67. patchXHR('setRequestHeader', function (orig) {
  68. return function (header, value) {
  69. if (header === '__setXHR_') {
  70. initializeUploadListener(this);
  71. var val = value(this);
  72. // fix for angular < 1.2.0
  73. if (val instanceof Function) {
  74. val(this);
  75. }
  76. } else {
  77. this.__requestHeaders = this.__requestHeaders || {};
  78. this.__requestHeaders[header] = value;
  79. orig.apply(this, arguments);
  80. }
  81. };
  82. });
  83. patchXHR('send', function (orig) {
  84. return function () {
  85. var xhr = this;
  86. if (arguments[0] && arguments[0].__isFileAPIShim) {
  87. var formData = arguments[0];
  88. var config = {
  89. url: xhr.__url,
  90. jsonp: false, //removes the callback form param
  91. cache: true, //removes the ?fileapiXXX in the url
  92. complete: function (err, fileApiXHR) {
  93. if (err && angular.isString(err) && err.indexOf('#2174') !== -1) {
  94. // this error seems to be fine the file is being uploaded properly.
  95. err = null;
  96. }
  97. xhr.__completed = true;
  98. if (!err && xhr.__listeners.load)
  99. xhr.__listeners.load({
  100. type: 'load',
  101. loaded: xhr.__loaded,
  102. total: xhr.__total,
  103. target: xhr,
  104. lengthComputable: true
  105. });
  106. if (!err && xhr.__listeners.loadend)
  107. xhr.__listeners.loadend({
  108. type: 'loadend',
  109. loaded: xhr.__loaded,
  110. total: xhr.__total,
  111. target: xhr,
  112. lengthComputable: true
  113. });
  114. if (err === 'abort' && xhr.__listeners.abort)
  115. xhr.__listeners.abort({
  116. type: 'abort',
  117. loaded: xhr.__loaded,
  118. total: xhr.__total,
  119. target: xhr,
  120. lengthComputable: true
  121. });
  122. if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function () {
  123. return (fileApiXHR.status === 0 && err && err !== 'abort') ? 500 : fileApiXHR.status;
  124. });
  125. if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function () {
  126. return fileApiXHR.statusText;
  127. });
  128. redefineProp(xhr, 'readyState', function () {
  129. return 4;
  130. });
  131. if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function () {
  132. return fileApiXHR.response;
  133. });
  134. var resp = fileApiXHR.responseText || (err && fileApiXHR.status === 0 && err !== 'abort' ? err : undefined);
  135. redefineProp(xhr, 'responseText', function () {
  136. return resp;
  137. });
  138. redefineProp(xhr, 'response', function () {
  139. return resp;
  140. });
  141. if (err) redefineProp(xhr, 'err', function () {
  142. return err;
  143. });
  144. xhr.__fileApiXHR = fileApiXHR;
  145. if (xhr.onreadystatechange) xhr.onreadystatechange();
  146. if (xhr.onload) xhr.onload();
  147. },
  148. progress: function (e) {
  149. e.target = xhr;
  150. if (xhr.__listeners.progress) xhr.__listeners.progress(e);
  151. xhr.__total = e.total;
  152. xhr.__loaded = e.loaded;
  153. if (e.total === e.loaded) {
  154. // fix flash issue that doesn't call complete if there is no response text from the server
  155. var _this = this;
  156. setTimeout(function () {
  157. if (!xhr.__completed) {
  158. xhr.getAllResponseHeaders = function () {
  159. };
  160. _this.complete(null, {status: 204, statusText: 'No Content'});
  161. }
  162. }, FileAPI.noContentTimeout || 10000);
  163. }
  164. },
  165. headers: xhr.__requestHeaders
  166. };
  167. config.data = {};
  168. config.files = {};
  169. for (var i = 0; i < formData.data.length; i++) {
  170. var item = formData.data[i];
  171. if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) {
  172. config.files[item.key] = item.val;
  173. } else {
  174. config.data[item.key] = item.val;
  175. }
  176. }
  177. setTimeout(function () {
  178. if (!FileAPI.hasFlash) {
  179. throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
  180. }
  181. xhr.__fileApiXHR = FileAPI.upload(config);
  182. }, 1);
  183. } else {
  184. if (this.__origError) {
  185. throw this.__origError;
  186. }
  187. orig.apply(xhr, arguments);
  188. }
  189. };
  190. });
  191. window.XMLHttpRequest.__isFileAPIShim = true;
  192. window.FormData = FormData = function () {
  193. return {
  194. append: function (key, val, name) {
  195. if (val.__isFileAPIBlobShim) {
  196. val = val.data[0];
  197. }
  198. this.data.push({
  199. key: key,
  200. val: val,
  201. name: name
  202. });
  203. },
  204. data: [],
  205. __isFileAPIShim: true
  206. };
  207. };
  208. window.Blob = Blob = function (b) {
  209. return {
  210. data: b,
  211. __isFileAPIBlobShim: true
  212. };
  213. };
  214. }
  215. })();
  216. (function () {
  217. /** @namespace FileAPI.forceLoad */
  218. /** @namespace window.FileAPI.jsUrl */
  219. /** @namespace window.FileAPI.jsPath */
  220. function isInputTypeFile(elem) {
  221. return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file';
  222. }
  223. function hasFlash() {
  224. try {
  225. var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  226. if (fo) return true;
  227. } catch (e) {
  228. if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) return true;
  229. }
  230. return false;
  231. }
  232. function getOffset(obj) {
  233. var left = 0, top = 0;
  234. if (window.jQuery) {
  235. return jQuery(obj).offset();
  236. }
  237. if (obj.offsetParent) {
  238. do {
  239. left += (obj.offsetLeft - obj.scrollLeft);
  240. top += (obj.offsetTop - obj.scrollTop);
  241. obj = obj.offsetParent;
  242. } while (obj);
  243. }
  244. return {
  245. left: left,
  246. top: top
  247. };
  248. }
  249. if (FileAPI.shouldLoad) {
  250. FileAPI.hasFlash = hasFlash();
  251. //load FileAPI
  252. if (FileAPI.forceLoad) {
  253. FileAPI.html5 = false;
  254. }
  255. if (!FileAPI.upload) {
  256. var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src;
  257. if (window.FileAPI.jsUrl) {
  258. jsUrl = window.FileAPI.jsUrl;
  259. } else if (window.FileAPI.jsPath) {
  260. basePath = window.FileAPI.jsPath;
  261. } else {
  262. for (i = 0; i < allScripts.length; i++) {
  263. src = allScripts[i].src;
  264. index = src.search(/\/ng\-file\-upload[\-a-zA-z0-9\.]*\.js/);
  265. if (index > -1) {
  266. basePath = src.substring(0, index + 1);
  267. break;
  268. }
  269. }
  270. }
  271. if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;
  272. script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js');
  273. document.getElementsByTagName('head')[0].appendChild(script);
  274. }
  275. FileAPI.ngfFixIE = function (elem, fileElem, changeFn) {
  276. if (!hasFlash()) {
  277. throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
  278. }
  279. var fixInputStyle = function () {
  280. var label = fileElem.parent();
  281. if (elem.attr('disabled')) {
  282. if (label) label.removeClass('js-fileapi-wrapper');
  283. } else {
  284. if (!fileElem.attr('__ngf_flash_')) {
  285. fileElem.unbind('change');
  286. fileElem.unbind('click');
  287. fileElem.bind('change', function (evt) {
  288. fileApiChangeFn.apply(this, [evt]);
  289. changeFn.apply(this, [evt]);
  290. });
  291. fileElem.attr('__ngf_flash_', 'true');
  292. }
  293. label.addClass('js-fileapi-wrapper');
  294. if (!isInputTypeFile(elem)) {
  295. label.css('position', 'absolute')
  296. .css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px')
  297. .css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px')
  298. .css('filter', 'alpha(opacity=0)').css('display', elem.css('display'))
  299. .css('overflow', 'hidden').css('z-index', '900000')
  300. .css('visibility', 'visible');
  301. fileElem.css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px')
  302. .css('position', 'absolute').css('top', '0px').css('left', '0px');
  303. }
  304. }
  305. };
  306. elem.bind('mouseenter', fixInputStyle);
  307. var fileApiChangeFn = function (evt) {
  308. var files = FileAPI.getFiles(evt);
  309. //just a double check for #233
  310. for (var i = 0; i < files.length; i++) {
  311. if (files[i].size === undefined) files[i].size = 0;
  312. if (files[i].name === undefined) files[i].name = 'file';
  313. if (files[i].type === undefined) files[i].type = 'undefined';
  314. }
  315. if (!evt.target) {
  316. evt.target = {};
  317. }
  318. evt.target.files = files;
  319. // if evt.target.files is not writable use helper field
  320. if (evt.target.files !== files) {
  321. evt.__files_ = files;
  322. }
  323. (evt.__files_ || evt.target.files).item = function (i) {
  324. return (evt.__files_ || evt.target.files)[i] || null;
  325. };
  326. };
  327. };
  328. FileAPI.disableFileInput = function (elem, disable) {
  329. if (disable) {
  330. elem.removeClass('js-fileapi-wrapper');
  331. } else {
  332. elem.addClass('js-fileapi-wrapper');
  333. }
  334. };
  335. }
  336. })();
  337. if (!window.FileReader) {
  338. window.FileReader = function () {
  339. var _this = this, loadStarted = false;
  340. this.listeners = {};
  341. this.addEventListener = function (type, fn) {
  342. _this.listeners[type] = _this.listeners[type] || [];
  343. _this.listeners[type].push(fn);
  344. };
  345. this.removeEventListener = function (type, fn) {
  346. if (_this.listeners[type]) _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1);
  347. };
  348. this.dispatchEvent = function (evt) {
  349. var list = _this.listeners[evt.type];
  350. if (list) {
  351. for (var i = 0; i < list.length; i++) {
  352. list[i].call(_this, evt);
  353. }
  354. }
  355. };
  356. this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null;
  357. var constructEvent = function (type, evt) {
  358. var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
  359. if (evt.result != null) e.target.result = evt.result;
  360. return e;
  361. };
  362. var listener = function (evt) {
  363. if (!loadStarted) {
  364. loadStarted = true;
  365. if (_this.onloadstart) _this.onloadstart(constructEvent('loadstart', evt));
  366. }
  367. var e;
  368. if (evt.type === 'load') {
  369. if (_this.onloadend) _this.onloadend(constructEvent('loadend', evt));
  370. e = constructEvent('load', evt);
  371. if (_this.onload) _this.onload(e);
  372. _this.dispatchEvent(e);
  373. } else if (evt.type === 'progress') {
  374. e = constructEvent('progress', evt);
  375. if (_this.onprogress) _this.onprogress(e);
  376. _this.dispatchEvent(e);
  377. } else {
  378. e = constructEvent('error', evt);
  379. if (_this.onerror) _this.onerror(e);
  380. _this.dispatchEvent(e);
  381. }
  382. };
  383. this.readAsDataURL = function (file) {
  384. FileAPI.readAsDataURL(file, listener);
  385. };
  386. this.readAsText = function (file) {
  387. FileAPI.readAsText(file, listener);
  388. };
  389. };
  390. }
  391. /**!
  392. * AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
  393. * progress, resize, thumbnail, preview, validation and CORS
  394. * @author Danial <danial.farid@gmail.com>
  395. * @version 12.2.13
  396. */
  397. if (window.XMLHttpRequest && !(window.FileAPI && FileAPI.shouldLoad)) {
  398. window.XMLHttpRequest.prototype.setRequestHeader = (function (orig) {
  399. return function (header, value) {
  400. if (header === '__setXHR_') {
  401. var val = value(this);
  402. // fix for angular < 1.2.0
  403. if (val instanceof Function) {
  404. val(this);
  405. }
  406. } else {
  407. orig.apply(this, arguments);
  408. }
  409. };
  410. })(window.XMLHttpRequest.prototype.setRequestHeader);
  411. }
  412. var ngFileUpload = angular.module('ngFileUpload', []);
  413. ngFileUpload.version = '12.2.13';
  414. ngFileUpload.service('UploadBase', ['$http', '$q', '$timeout', function ($http, $q, $timeout) {
  415. var upload = this;
  416. upload.promisesCount = 0;
  417. this.isResumeSupported = function () {
  418. return window.Blob && window.Blob.prototype.slice;
  419. };
  420. var resumeSupported = this.isResumeSupported();
  421. function sendHttp(config) {
  422. config.method = config.method || 'POST';
  423. config.headers = config.headers || {};
  424. var deferred = config._deferred = config._deferred || $q.defer();
  425. var promise = deferred.promise;
  426. function notifyProgress(e) {
  427. if (deferred.notify) {
  428. deferred.notify(e);
  429. }
  430. if (promise.progressFunc) {
  431. $timeout(function () {
  432. promise.progressFunc(e);
  433. });
  434. }
  435. }
  436. function getNotifyEvent(n) {
  437. if (config._start != null && resumeSupported) {
  438. return {
  439. loaded: n.loaded + config._start,
  440. total: (config._file && config._file.size) || n.total,
  441. type: n.type, config: config,
  442. lengthComputable: true, target: n.target
  443. };
  444. } else {
  445. return n;
  446. }
  447. }
  448. if (!config.disableProgress) {
  449. config.headers.__setXHR_ = function () {
  450. return function (xhr) {
  451. if (!xhr || !xhr.upload || !xhr.upload.addEventListener) return;
  452. config.__XHR = xhr;
  453. if (config.xhrFn) config.xhrFn(xhr);
  454. xhr.upload.addEventListener('progress', function (e) {
  455. e.config = config;
  456. notifyProgress(getNotifyEvent(e));
  457. }, false);
  458. //fix for firefox not firing upload progress end, also IE8-9
  459. xhr.upload.addEventListener('load', function (e) {
  460. if (e.lengthComputable) {
  461. e.config = config;
  462. notifyProgress(getNotifyEvent(e));
  463. }
  464. }, false);
  465. };
  466. };
  467. }
  468. function uploadWithAngular() {
  469. $http(config).then(function (r) {
  470. if (resumeSupported && config._chunkSize && !config._finished && config._file) {
  471. var fileSize = config._file && config._file.size || 0;
  472. notifyProgress({
  473. loaded: Math.min(config._end, fileSize),
  474. total: fileSize,
  475. config: config,
  476. type: 'progress'
  477. }
  478. );
  479. upload.upload(config, true);
  480. } else {
  481. if (config._finished) delete config._finished;
  482. deferred.resolve(r);
  483. }
  484. }, function (e) {
  485. deferred.reject(e);
  486. }, function (n) {
  487. deferred.notify(n);
  488. }
  489. );
  490. }
  491. if (!resumeSupported) {
  492. uploadWithAngular();
  493. } else if (config._chunkSize && config._end && !config._finished) {
  494. config._start = config._end;
  495. config._end += config._chunkSize;
  496. uploadWithAngular();
  497. } else if (config.resumeSizeUrl) {
  498. $http.get(config.resumeSizeUrl).then(function (resp) {
  499. if (config.resumeSizeResponseReader) {
  500. config._start = config.resumeSizeResponseReader(resp.data);
  501. } else {
  502. config._start = parseInt((resp.data.size == null ? resp.data : resp.data.size).toString());
  503. }
  504. if (config._chunkSize) {
  505. config._end = config._start + config._chunkSize;
  506. }
  507. uploadWithAngular();
  508. }, function (e) {
  509. throw e;
  510. });
  511. } else if (config.resumeSize) {
  512. config.resumeSize().then(function (size) {
  513. config._start = size;
  514. if (config._chunkSize) {
  515. config._end = config._start + config._chunkSize;
  516. }
  517. uploadWithAngular();
  518. }, function (e) {
  519. throw e;
  520. });
  521. } else {
  522. if (config._chunkSize) {
  523. config._start = 0;
  524. config._end = config._start + config._chunkSize;
  525. }
  526. uploadWithAngular();
  527. }
  528. promise.success = function (fn) {
  529. promise.then(function (response) {
  530. fn(response.data, response.status, response.headers, config);
  531. });
  532. return promise;
  533. };
  534. promise.error = function (fn) {
  535. promise.then(null, function (response) {
  536. fn(response.data, response.status, response.headers, config);
  537. });
  538. return promise;
  539. };
  540. promise.progress = function (fn) {
  541. promise.progressFunc = fn;
  542. promise.then(null, null, function (n) {
  543. fn(n);
  544. });
  545. return promise;
  546. };
  547. promise.abort = promise.pause = function () {
  548. if (config.__XHR) {
  549. $timeout(function () {
  550. config.__XHR.abort();
  551. });
  552. }
  553. return promise;
  554. };
  555. promise.xhr = function (fn) {
  556. config.xhrFn = (function (origXhrFn) {
  557. return function () {
  558. if (origXhrFn) origXhrFn.apply(promise, arguments);
  559. fn.apply(promise, arguments);
  560. };
  561. })(config.xhrFn);
  562. return promise;
  563. };
  564. upload.promisesCount++;
  565. if (promise['finally'] && promise['finally'] instanceof Function) {
  566. promise['finally'](function () {
  567. upload.promisesCount--;
  568. });
  569. }
  570. return promise;
  571. }
  572. this.isUploadInProgress = function () {
  573. return upload.promisesCount > 0;
  574. };
  575. this.rename = function (file, name) {
  576. file.ngfName = name;
  577. return file;
  578. };
  579. this.jsonBlob = function (val) {
  580. if (val != null && !angular.isString(val)) {
  581. val = JSON.stringify(val);
  582. }
  583. var blob = new window.Blob([val], {type: 'application/json'});
  584. blob._ngfBlob = true;
  585. return blob;
  586. };
  587. this.json = function (val) {
  588. return angular.toJson(val);
  589. };
  590. function copy(obj) {
  591. var clone = {};
  592. for (var key in obj) {
  593. if (obj.hasOwnProperty(key)) {
  594. clone[key] = obj[key];
  595. }
  596. }
  597. return clone;
  598. }
  599. this.isFile = function (file) {
  600. return file != null && (file instanceof window.Blob || (file.flashId && file.name && file.size));
  601. };
  602. this.upload = function (config, internal) {
  603. function toResumeFile(file, formData) {
  604. if (file._ngfBlob) return file;
  605. config._file = config._file || file;
  606. if (config._start != null && resumeSupported) {
  607. if (config._end && config._end >= file.size) {
  608. config._finished = true;
  609. config._end = file.size;
  610. }
  611. var slice = file.slice(config._start, config._end || file.size);
  612. slice.name = file.name;
  613. slice.ngfName = file.ngfName;
  614. if (config._chunkSize) {
  615. formData.append('_chunkSize', config._chunkSize);
  616. formData.append('_currentChunkSize', config._end - config._start);
  617. formData.append('_chunkNumber', Math.floor(config._start / config._chunkSize));
  618. formData.append('_totalSize', config._file.size);
  619. }
  620. return slice;
  621. }
  622. return file;
  623. }
  624. function addFieldToFormData(formData, val, key) {
  625. if (val !== undefined) {
  626. if (angular.isDate(val)) {
  627. val = val.toISOString();
  628. }
  629. if (angular.isString(val)) {
  630. formData.append(key, val);
  631. } else if (upload.isFile(val)) {
  632. var file = toResumeFile(val, formData);
  633. var split = key.split(',');
  634. if (split[1]) {
  635. file.ngfName = split[1].replace(/^\s+|\s+$/g, '');
  636. key = split[0];
  637. }
  638. config._fileKey = config._fileKey || key;
  639. formData.append(key, file, file.ngfName || file.name);
  640. } else {
  641. if (angular.isObject(val)) {
  642. if (val.$$ngfCircularDetection) throw 'ngFileUpload: Circular reference in config.data. Make sure specified data for Upload.upload() has no circular reference: ' + key;
  643. val.$$ngfCircularDetection = true;
  644. try {
  645. for (var k in val) {
  646. if (val.hasOwnProperty(k) && k !== '$$ngfCircularDetection') {
  647. var objectKey = config.objectKey == null ? '[i]' : config.objectKey;
  648. if (val.length && parseInt(k) > -1) {
  649. objectKey = config.arrayKey == null ? objectKey : config.arrayKey;
  650. }
  651. addFieldToFormData(formData, val[k], key + objectKey.replace(/[ik]/g, k));
  652. }
  653. }
  654. } finally {
  655. delete val.$$ngfCircularDetection;
  656. }
  657. } else {
  658. formData.append(key, val);
  659. }
  660. }
  661. }
  662. }
  663. function digestConfig() {
  664. config._chunkSize = upload.translateScalars(config.resumeChunkSize);
  665. config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null;
  666. config.headers = config.headers || {};
  667. config.headers['Content-Type'] = undefined;
  668. config.transformRequest = config.transformRequest ?
  669. (angular.isArray(config.transformRequest) ?
  670. config.transformRequest : [config.transformRequest]) : [];
  671. config.transformRequest.push(function (data) {
  672. var formData = new window.FormData(), key;
  673. data = data || config.fields || {};
  674. if (config.file) {
  675. data.file = config.file;
  676. }
  677. for (key in data) {
  678. if (data.hasOwnProperty(key)) {
  679. var val = data[key];
  680. if (config.formDataAppender) {
  681. config.formDataAppender(formData, key, val);
  682. } else {
  683. addFieldToFormData(formData, val, key);
  684. }
  685. }
  686. }
  687. return formData;
  688. });
  689. }
  690. if (!internal) config = copy(config);
  691. if (!config._isDigested) {
  692. config._isDigested = true;
  693. digestConfig();
  694. }
  695. return sendHttp(config);
  696. };
  697. this.http = function (config) {
  698. config = copy(config);
  699. config.transformRequest = config.transformRequest || function (data) {
  700. if ((window.ArrayBuffer && data instanceof window.ArrayBuffer) || data instanceof window.Blob) {
  701. return data;
  702. }
  703. return $http.defaults.transformRequest[0].apply(this, arguments);
  704. };
  705. config._chunkSize = upload.translateScalars(config.resumeChunkSize);
  706. config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null;
  707. return sendHttp(config);
  708. };
  709. this.translateScalars = function (str) {
  710. if (angular.isString(str)) {
  711. if (str.search(/kb/i) === str.length - 2) {
  712. return parseFloat(str.substring(0, str.length - 2) * 1024);
  713. } else if (str.search(/mb/i) === str.length - 2) {
  714. return parseFloat(str.substring(0, str.length - 2) * 1048576);
  715. } else if (str.search(/gb/i) === str.length - 2) {
  716. return parseFloat(str.substring(0, str.length - 2) * 1073741824);
  717. } else if (str.search(/b/i) === str.length - 1) {
  718. return parseFloat(str.substring(0, str.length - 1));
  719. } else if (str.search(/s/i) === str.length - 1) {
  720. return parseFloat(str.substring(0, str.length - 1));
  721. } else if (str.search(/m/i) === str.length - 1) {
  722. return parseFloat(str.substring(0, str.length - 1) * 60);
  723. } else if (str.search(/h/i) === str.length - 1) {
  724. return parseFloat(str.substring(0, str.length - 1) * 3600);
  725. }
  726. }
  727. return str;
  728. };
  729. this.urlToBlob = function(url) {
  730. var defer = $q.defer();
  731. $http({url: url, method: 'get', responseType: 'arraybuffer'}).then(function (resp) {
  732. var arrayBufferView = new Uint8Array(resp.data);
  733. var type = resp.headers('content-type') || 'image/WebP';
  734. var blob = new window.Blob([arrayBufferView], {type: type});
  735. var matches = url.match(/.*\/(.+?)(\?.*)?$/);
  736. if (matches.length > 1) {
  737. blob.name = matches[1];
  738. }
  739. defer.resolve(blob);
  740. }, function (e) {
  741. defer.reject(e);
  742. });
  743. return defer.promise;
  744. };
  745. this.setDefaults = function (defaults) {
  746. this.defaults = defaults || {};
  747. };
  748. this.defaults = {};
  749. this.version = ngFileUpload.version;
  750. }
  751. ]);
  752. ngFileUpload.service('Upload', ['$parse', '$timeout', '$compile', '$q', 'UploadExif', function ($parse, $timeout, $compile, $q, UploadExif) {
  753. var upload = UploadExif;
  754. upload.getAttrWithDefaults = function (attr, name) {
  755. if (attr[name] != null) return attr[name];
  756. var def = upload.defaults[name];
  757. return (def == null ? def : (angular.isString(def) ? def : JSON.stringify(def)));
  758. };
  759. upload.attrGetter = function (name, attr, scope, params) {
  760. var attrVal = this.getAttrWithDefaults(attr, name);
  761. if (scope) {
  762. try {
  763. if (params) {
  764. return $parse(attrVal)(scope, params);
  765. } else {
  766. return $parse(attrVal)(scope);
  767. }
  768. } catch (e) {
  769. // hangle string value without single qoute
  770. if (name.search(/min|max|pattern/i)) {
  771. return attrVal;
  772. } else {
  773. throw e;
  774. }
  775. }
  776. } else {
  777. return attrVal;
  778. }
  779. };
  780. upload.shouldUpdateOn = function (type, attr, scope) {
  781. var modelOptions = upload.attrGetter('ngfModelOptions', attr, scope);
  782. if (modelOptions && modelOptions.updateOn) {
  783. return modelOptions.updateOn.split(' ').indexOf(type) > -1;
  784. }
  785. return true;
  786. };
  787. upload.emptyPromise = function () {
  788. var d = $q.defer();
  789. var args = arguments;
  790. $timeout(function () {
  791. d.resolve.apply(d, args);
  792. });
  793. return d.promise;
  794. };
  795. upload.rejectPromise = function () {
  796. var d = $q.defer();
  797. var args = arguments;
  798. $timeout(function () {
  799. d.reject.apply(d, args);
  800. });
  801. return d.promise;
  802. };
  803. upload.happyPromise = function (promise, data) {
  804. var d = $q.defer();
  805. promise.then(function (result) {
  806. d.resolve(result);
  807. }, function (error) {
  808. $timeout(function () {
  809. throw error;
  810. });
  811. d.resolve(data);
  812. });
  813. return d.promise;
  814. };
  815. function applyExifRotations(files, attr, scope) {
  816. var promises = [upload.emptyPromise()];
  817. angular.forEach(files, function (f, i) {
  818. if (f.type.indexOf('image/jpeg') === 0 && upload.attrGetter('ngfFixOrientation', attr, scope, {$file: f})) {
  819. promises.push(upload.happyPromise(upload.applyExifRotation(f), f).then(function (fixedFile) {
  820. files.splice(i, 1, fixedFile);
  821. }));
  822. }
  823. });
  824. return $q.all(promises);
  825. }
  826. function resizeFile(files, attr, scope, ngModel) {
  827. var resizeVal = upload.attrGetter('ngfResize', attr, scope);
  828. if (!resizeVal || !upload.isResizeSupported() || !files.length) return upload.emptyPromise();
  829. if (resizeVal instanceof Function) {
  830. var defer = $q.defer();
  831. return resizeVal(files).then(function (p) {
  832. resizeWithParams(p, files, attr, scope, ngModel).then(function (r) {
  833. defer.resolve(r);
  834. }, function (e) {
  835. defer.reject(e);
  836. });
  837. }, function (e) {
  838. defer.reject(e);
  839. });
  840. } else {
  841. return resizeWithParams(resizeVal, files, attr, scope, ngModel);
  842. }
  843. }
  844. function resizeWithParams(params, files, attr, scope, ngModel) {
  845. var promises = [upload.emptyPromise()];
  846. function handleFile(f, i) {
  847. if (f.type.indexOf('image') === 0) {
  848. if (params.pattern && !upload.validatePattern(f, params.pattern)) return;
  849. params.resizeIf = function (width, height) {
  850. return upload.attrGetter('ngfResizeIf', attr, scope,
  851. {$width: width, $height: height, $file: f});
  852. };
  853. var promise = upload.resize(f, params);
  854. promises.push(promise);
  855. promise.then(function (resizedFile) {
  856. files.splice(i, 1, resizedFile);
  857. }, function (e) {
  858. f.$error = 'resize';
  859. (f.$errorMessages = (f.$errorMessages || {})).resize = true;
  860. f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name);
  861. ngModel.$ngfValidations.push({name: 'resize', valid: false});
  862. upload.applyModelValidation(ngModel, files);
  863. });
  864. }
  865. }
  866. for (var i = 0; i < files.length; i++) {
  867. handleFile(files[i], i);
  868. }
  869. return $q.all(promises);
  870. }
  871. upload.updateModel = function (ngModel, attr, scope, fileChange, files, evt, noDelay) {
  872. function update(files, invalidFiles, newFiles, dupFiles, isSingleModel) {
  873. attr.$$ngfPrevValidFiles = files;
  874. attr.$$ngfPrevInvalidFiles = invalidFiles;
  875. var file = files && files.length ? files[0] : null;
  876. var invalidFile = invalidFiles && invalidFiles.length ? invalidFiles[0] : null;
  877. if (ngModel) {
  878. upload.applyModelValidation(ngModel, files);
  879. ngModel.$setViewValue(isSingleModel ? file : files);
  880. }
  881. if (fileChange) {
  882. $parse(fileChange)(scope, {
  883. $files: files,
  884. $file: file,
  885. $newFiles: newFiles,
  886. $duplicateFiles: dupFiles,
  887. $invalidFiles: invalidFiles,
  888. $invalidFile: invalidFile,
  889. $event: evt
  890. });
  891. }
  892. var invalidModel = upload.attrGetter('ngfModelInvalid', attr);
  893. if (invalidModel) {
  894. $timeout(function () {
  895. $parse(invalidModel).assign(scope, isSingleModel ? invalidFile : invalidFiles);
  896. });
  897. }
  898. $timeout(function () {
  899. // scope apply changes
  900. });
  901. }
  902. var allNewFiles, dupFiles = [], prevValidFiles, prevInvalidFiles,
  903. invalids = [], valids = [];
  904. function removeDuplicates() {
  905. function equals(f1, f2) {
  906. return f1.name === f2.name && (f1.$ngfOrigSize || f1.size) === (f2.$ngfOrigSize || f2.size) &&
  907. f1.type === f2.type;
  908. }
  909. function isInPrevFiles(f) {
  910. var j;
  911. for (j = 0; j < prevValidFiles.length; j++) {
  912. if (equals(f, prevValidFiles[j])) {
  913. return true;
  914. }
  915. }
  916. for (j = 0; j < prevInvalidFiles.length; j++) {
  917. if (equals(f, prevInvalidFiles[j])) {
  918. return true;
  919. }
  920. }
  921. return false;
  922. }
  923. if (files) {
  924. allNewFiles = [];
  925. dupFiles = [];
  926. for (var i = 0; i < files.length; i++) {
  927. if (isInPrevFiles(files[i])) {
  928. dupFiles.push(files[i]);
  929. } else {
  930. allNewFiles.push(files[i]);
  931. }
  932. }
  933. }
  934. }
  935. function toArray(v) {
  936. return angular.isArray(v) ? v : [v];
  937. }
  938. function resizeAndUpdate() {
  939. function updateModel() {
  940. $timeout(function () {
  941. update(keep ? prevValidFiles.concat(valids) : valids,
  942. keep ? prevInvalidFiles.concat(invalids) : invalids,
  943. files, dupFiles, isSingleModel);
  944. }, options && options.debounce ? options.debounce.change || options.debounce : 0);
  945. }
  946. var resizingFiles = validateAfterResize ? allNewFiles : valids;
  947. resizeFile(resizingFiles, attr, scope, ngModel).then(function () {
  948. if (validateAfterResize) {
  949. upload.validate(allNewFiles, keep ? prevValidFiles.length : 0, ngModel, attr, scope)
  950. .then(function (validationResult) {
  951. valids = validationResult.validsFiles;
  952. invalids = validationResult.invalidsFiles;
  953. updateModel();
  954. });
  955. } else {
  956. updateModel();
  957. }
  958. }, function () {
  959. for (var i = 0; i < resizingFiles.length; i++) {
  960. var f = resizingFiles[i];
  961. if (f.$error === 'resize') {
  962. var index = valids.indexOf(f);
  963. if (index > -1) {
  964. valids.splice(index, 1);
  965. invalids.push(f);
  966. }
  967. updateModel();
  968. }
  969. }
  970. });
  971. }
  972. prevValidFiles = attr.$$ngfPrevValidFiles || [];
  973. prevInvalidFiles = attr.$$ngfPrevInvalidFiles || [];
  974. if (ngModel && ngModel.$modelValue) {
  975. prevValidFiles = toArray(ngModel.$modelValue);
  976. }
  977. var keep = upload.attrGetter('ngfKeep', attr, scope);
  978. allNewFiles = (files || []).slice(0);
  979. if (keep === 'distinct' || upload.attrGetter('ngfKeepDistinct', attr, scope) === true) {
  980. removeDuplicates(attr, scope);
  981. }
  982. var isSingleModel = !keep && !upload.attrGetter('ngfMultiple', attr, scope) && !upload.attrGetter('multiple', attr);
  983. if (keep && !allNewFiles.length) return;
  984. upload.attrGetter('ngfBeforeModelChange', attr, scope, {
  985. $files: files,
  986. $file: files && files.length ? files[0] : null,
  987. $newFiles: allNewFiles,
  988. $duplicateFiles: dupFiles,
  989. $event: evt
  990. });
  991. var validateAfterResize = upload.attrGetter('ngfValidateAfterResize', attr, scope);
  992. var options = upload.attrGetter('ngfModelOptions', attr, scope);
  993. upload.validate(allNewFiles, keep ? prevValidFiles.length : 0, ngModel, attr, scope)
  994. .then(function (validationResult) {
  995. if (noDelay) {
  996. update(allNewFiles, [], files, dupFiles, isSingleModel);
  997. } else {
  998. if ((!options || !options.allowInvalid) && !validateAfterResize) {
  999. valids = validationResult.validFiles;
  1000. invalids = validationResult.invalidFiles;
  1001. } else {
  1002. valids = allNewFiles;
  1003. }
  1004. if (upload.attrGetter('ngfFixOrientation', attr, scope) && upload.isExifSupported()) {
  1005. applyExifRotations(valids, attr, scope).then(function () {
  1006. resizeAndUpdate();
  1007. });
  1008. } else {
  1009. resizeAndUpdate();
  1010. }
  1011. }
  1012. });
  1013. };
  1014. return upload;
  1015. }]);
  1016. ngFileUpload.directive('ngfSelect', ['$parse', '$timeout', '$compile', 'Upload', function ($parse, $timeout, $compile, Upload) {
  1017. var generatedElems = [];
  1018. function isDelayedClickSupported(ua) {
  1019. // fix for android native browser < 4.4 and safari windows
  1020. var m = ua.match(/Android[^\d]*(\d+)\.(\d+)/);
  1021. if (m && m.length > 2) {
  1022. var v = Upload.defaults.androidFixMinorVersion || 4;
  1023. return parseInt(m[1]) < 4 || (parseInt(m[1]) === v && parseInt(m[2]) < v);
  1024. }
  1025. // safari on windows
  1026. return ua.indexOf('Chrome') === -1 && /.*Windows.*Safari.*/.test(ua);
  1027. }
  1028. function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, upload) {
  1029. /** @namespace attr.ngfSelect */
  1030. /** @namespace attr.ngfChange */
  1031. /** @namespace attr.ngModel */
  1032. /** @namespace attr.ngfModelOptions */
  1033. /** @namespace attr.ngfMultiple */
  1034. /** @namespace attr.ngfCapture */
  1035. /** @namespace attr.ngfValidate */
  1036. /** @namespace attr.ngfKeep */
  1037. var attrGetter = function (name, scope) {
  1038. return upload.attrGetter(name, attr, scope);
  1039. };
  1040. function isInputTypeFile() {
  1041. return elem[0].tagName.toLowerCase() === 'input' && attr.type && attr.type.toLowerCase() === 'file';
  1042. }
  1043. function fileChangeAttr() {
  1044. return attrGetter('ngfChange') || attrGetter('ngfSelect');
  1045. }
  1046. function changeFn(evt) {
  1047. if (upload.shouldUpdateOn('change', attr, scope)) {
  1048. var fileList = evt.__files_ || (evt.target && evt.target.files), files = [];
  1049. /* Handle duplicate call in IE11 */
  1050. if (!fileList) return;
  1051. for (var i = 0; i < fileList.length; i++) {
  1052. files.push(fileList[i]);
  1053. }
  1054. upload.updateModel(ngModel, attr, scope, fileChangeAttr(),
  1055. files.length ? files : null, evt);
  1056. }
  1057. }
  1058. upload.registerModelChangeValidator(ngModel, attr, scope);
  1059. var unwatches = [];
  1060. if (attrGetter('ngfMultiple')) {
  1061. unwatches.push(scope.$watch(attrGetter('ngfMultiple'), function () {
  1062. fileElem.attr('multiple', attrGetter('ngfMultiple', scope));
  1063. }));
  1064. }
  1065. if (attrGetter('ngfCapture')) {
  1066. unwatches.push(scope.$watch(attrGetter('ngfCapture'), function () {
  1067. fileElem.attr('capture', attrGetter('ngfCapture', scope));
  1068. }));
  1069. }
  1070. if (attrGetter('ngfAccept')) {
  1071. unwatches.push(scope.$watch(attrGetter('ngfAccept'), function () {
  1072. fileElem.attr('accept', attrGetter('ngfAccept', scope));
  1073. }));
  1074. }
  1075. unwatches.push(attr.$observe('accept', function () {
  1076. fileElem.attr('accept', attrGetter('accept'));
  1077. }));
  1078. function bindAttrToFileInput(fileElem, label) {
  1079. function updateId(val) {
  1080. fileElem.attr('id', 'ngf-' + val);
  1081. label.attr('id', 'ngf-label-' + val);
  1082. }
  1083. for (var i = 0; i < elem[0].attributes.length; i++) {
  1084. var attribute = elem[0].attributes[i];
  1085. if (attribute.name !== 'type' && attribute.name !== 'class' && attribute.name !== 'style') {
  1086. if (attribute.name === 'id') {
  1087. updateId(attribute.value);
  1088. unwatches.push(attr.$observe('id', updateId));
  1089. } else {
  1090. fileElem.attr(attribute.name, (!attribute.value && (attribute.name === 'required' ||
  1091. attribute.name === 'multiple')) ? attribute.name : attribute.value);
  1092. }
  1093. }
  1094. }
  1095. }
  1096. function createFileInput() {
  1097. if (isInputTypeFile()) {
  1098. return elem;
  1099. }
  1100. var fileElem = angular.element('<input type="file">');
  1101. var label = angular.element('<label>upload</label>');
  1102. label.css('visibility', 'hidden').css('position', 'absolute').css('overflow', 'hidden')
  1103. .css('width', '0px').css('height', '0px').css('border', 'none')
  1104. .css('margin', '0px').css('padding', '0px').attr('tabindex', '-1');
  1105. bindAttrToFileInput(fileElem, label);
  1106. generatedElems.push({el: elem, ref: label});
  1107. document.body.appendChild(label.append(fileElem)[0]);
  1108. return fileElem;
  1109. }
  1110. function clickHandler(evt) {
  1111. if (elem.attr('disabled')) return false;
  1112. if (attrGetter('ngfSelectDisabled', scope)) return;
  1113. var r = detectSwipe(evt);
  1114. // prevent the click if it is a swipe
  1115. if (r != null) return r;
  1116. resetModel(evt);
  1117. // fix for md when the element is removed from the DOM and added back #460
  1118. try {
  1119. if (!isInputTypeFile() && !document.body.contains(fileElem[0])) {
  1120. generatedElems.push({el: elem, ref: fileElem.parent()});
  1121. document.body.appendChild(fileElem.parent()[0]);
  1122. fileElem.bind('change', changeFn);
  1123. }
  1124. } catch (e) {/*ignore*/
  1125. }
  1126. if (isDelayedClickSupported(navigator.userAgent)) {
  1127. setTimeout(function () {
  1128. fileElem[0].click();
  1129. }, 0);
  1130. } else {
  1131. fileElem[0].click();
  1132. }
  1133. return false;
  1134. }
  1135. var initialTouchStartY = 0;
  1136. var initialTouchStartX = 0;
  1137. function detectSwipe(evt) {
  1138. var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches);
  1139. if (touches) {
  1140. if (evt.type === 'touchstart') {
  1141. initialTouchStartX = touches[0].clientX;
  1142. initialTouchStartY = touches[0].clientY;
  1143. return true; // don't block event default
  1144. } else {
  1145. // prevent scroll from triggering event
  1146. if (evt.type === 'touchend') {
  1147. var currentX = touches[0].clientX;
  1148. var currentY = touches[0].clientY;
  1149. if ((Math.abs(currentX - initialTouchStartX) > 20) ||
  1150. (Math.abs(currentY - initialTouchStartY) > 20)) {
  1151. evt.stopPropagation();
  1152. evt.preventDefault();
  1153. return false;
  1154. }
  1155. }
  1156. return true;
  1157. }
  1158. }
  1159. }
  1160. var fileElem = elem;
  1161. function resetModel(evt) {
  1162. if (upload.shouldUpdateOn('click', attr, scope) && fileElem.val()) {
  1163. fileElem.val(null);
  1164. upload.updateModel(ngModel, attr, scope, fileChangeAttr(), null, evt, true);
  1165. }
  1166. }
  1167. if (!isInputTypeFile()) {
  1168. fileElem = createFileInput();
  1169. }
  1170. fileElem.bind('change', changeFn);
  1171. if (!isInputTypeFile()) {
  1172. elem.bind('click touchstart touchend', clickHandler);
  1173. } else {
  1174. elem.bind('click', resetModel);
  1175. }
  1176. function ie10SameFileSelectFix(evt) {
  1177. if (fileElem && !fileElem.attr('__ngf_ie10_Fix_')) {
  1178. if (!fileElem[0].parentNode) {
  1179. fileElem = null;
  1180. return;
  1181. }
  1182. evt.preventDefault();
  1183. evt.stopPropagation();
  1184. fileElem.unbind('click');
  1185. var clone = fileElem.clone();
  1186. fileElem.replaceWith(clone);
  1187. fileElem = clone;
  1188. fileElem.attr('__ngf_ie10_Fix_', 'true');
  1189. fileElem.bind('change', changeFn);
  1190. fileElem.bind('click', ie10SameFileSelectFix);
  1191. fileElem[0].click();
  1192. return false;
  1193. } else {
  1194. fileElem.removeAttr('__ngf_ie10_Fix_');
  1195. }
  1196. }
  1197. if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
  1198. fileElem.bind('click', ie10SameFileSelectFix);
  1199. }
  1200. if (ngModel) ngModel.$formatters.push(function (val) {
  1201. if (val == null || val.length === 0) {
  1202. if (fileElem.val()) {
  1203. fileElem.val(null);
  1204. }
  1205. }
  1206. return val;
  1207. });
  1208. scope.$on('$destroy', function () {
  1209. if (!isInputTypeFile()) fileElem.parent().remove();
  1210. angular.forEach(unwatches, function (unwatch) {
  1211. unwatch();
  1212. });
  1213. });
  1214. $timeout(function () {
  1215. for (var i = 0; i < generatedElems.length; i++) {
  1216. var g = generatedElems[i];
  1217. if (!document.body.contains(g.el[0])) {
  1218. generatedElems.splice(i, 1);
  1219. g.ref.remove();
  1220. }
  1221. }
  1222. });
  1223. if (window.FileAPI && window.FileAPI.ngfFixIE) {
  1224. window.FileAPI.ngfFixIE(elem, fileElem, changeFn);
  1225. }
  1226. }
  1227. return {
  1228. restrict: 'AEC',
  1229. require: '?ngModel',
  1230. link: function (scope, elem, attr, ngModel) {
  1231. linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, Upload);
  1232. }
  1233. };
  1234. }]);
  1235. (function () {
  1236. ngFileUpload.service('UploadDataUrl', ['UploadBase', '$timeout', '$q', function (UploadBase, $timeout, $q) {
  1237. var upload = UploadBase;
  1238. upload.base64DataUrl = function (file) {
  1239. if (angular.isArray(file)) {
  1240. var d = $q.defer(), count = 0;
  1241. angular.forEach(file, function (f) {
  1242. upload.dataUrl(f, true)['finally'](function () {
  1243. count++;
  1244. if (count === file.length) {
  1245. var urls = [];
  1246. angular.forEach(file, function (ff) {
  1247. urls.push(ff.$ngfDataUrl);
  1248. });
  1249. d.resolve(urls, file);
  1250. }
  1251. });
  1252. });
  1253. return d.promise;
  1254. } else {
  1255. return upload.dataUrl(file, true);
  1256. }
  1257. };
  1258. upload.dataUrl = function (file, disallowObjectUrl) {
  1259. if (!file) return upload.emptyPromise(file, file);
  1260. if ((disallowObjectUrl && file.$ngfDataUrl != null) || (!disallowObjectUrl && file.$ngfBlobUrl != null)) {
  1261. return upload.emptyPromise(disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl, file);
  1262. }
  1263. var p = disallowObjectUrl ? file.$$ngfDataUrlPromise : file.$$ngfBlobUrlPromise;
  1264. if (p) return p;
  1265. var deferred = $q.defer();
  1266. $timeout(function () {
  1267. if (window.FileReader && file &&
  1268. (!window.FileAPI || navigator.userAgent.indexOf('MSIE 8') === -1 || file.size < 20000) &&
  1269. (!window.FileAPI || navigator.userAgent.indexOf('MSIE 9') === -1 || file.size < 4000000)) {
  1270. //prefer URL.createObjectURL for handling refrences to files of all sizes
  1271. //since it doesn´t build a large string in memory
  1272. var URL = window.URL || window.webkitURL;
  1273. if (URL && URL.createObjectURL && !disallowObjectUrl) {
  1274. var url;
  1275. try {
  1276. url = URL.createObjectURL(file);
  1277. } catch (e) {
  1278. $timeout(function () {
  1279. file.$ngfBlobUrl = '';
  1280. deferred.reject();
  1281. });
  1282. return;
  1283. }
  1284. $timeout(function () {
  1285. file.$ngfBlobUrl = url;
  1286. if (url) {
  1287. deferred.resolve(url, file);
  1288. upload.blobUrls = upload.blobUrls || [];
  1289. upload.blobUrlsTotalSize = upload.blobUrlsTotalSize || 0;
  1290. upload.blobUrls.push({url: url, size: file.size});
  1291. upload.blobUrlsTotalSize += file.size || 0;
  1292. var maxMemory = upload.defaults.blobUrlsMaxMemory || 268435456;
  1293. var maxLength = upload.defaults.blobUrlsMaxQueueSize || 200;
  1294. while ((upload.blobUrlsTotalSize > maxMemory || upload.blobUrls.length > maxLength) && upload.blobUrls.length > 1) {
  1295. var obj = upload.blobUrls.splice(0, 1)[0];
  1296. URL.revokeObjectURL(obj.url);
  1297. upload.blobUrlsTotalSize -= obj.size;
  1298. }
  1299. }
  1300. });
  1301. } else {
  1302. var fileReader = new FileReader();
  1303. fileReader.onload = function (e) {
  1304. $timeout(function () {
  1305. file.$ngfDataUrl = e.target.result;
  1306. deferred.resolve(e.target.result, file);
  1307. $timeout(function () {
  1308. delete file.$ngfDataUrl;
  1309. }, 1000);
  1310. });
  1311. };
  1312. fileReader.onerror = function () {
  1313. $timeout(function () {
  1314. file.$ngfDataUrl = '';
  1315. deferred.reject();
  1316. });
  1317. };
  1318. fileReader.readAsDataURL(file);
  1319. }
  1320. } else {
  1321. $timeout(function () {
  1322. file[disallowObjectUrl ? '$ngfDataUrl' : '$ngfBlobUrl'] = '';
  1323. deferred.reject();
  1324. });
  1325. }
  1326. });
  1327. if (disallowObjectUrl) {
  1328. p = file.$$ngfDataUrlPromise = deferred.promise;
  1329. } else {
  1330. p = file.$$ngfBlobUrlPromise = deferred.promise;
  1331. }
  1332. p['finally'](function () {
  1333. delete file[disallowObjectUrl ? '$$ngfDataUrlPromise' : '$$ngfBlobUrlPromise'];
  1334. });
  1335. return p;
  1336. };
  1337. return upload;
  1338. }]);
  1339. function getTagType(el) {
  1340. if (el.tagName.toLowerCase() === 'img') return 'image';
  1341. if (el.tagName.toLowerCase() === 'audio') return 'audio';
  1342. if (el.tagName.toLowerCase() === 'video') return 'video';
  1343. return /./;
  1344. }
  1345. function linkFileDirective(Upload, $timeout, scope, elem, attr, directiveName, resizeParams, isBackground) {
  1346. function constructDataUrl(file) {
  1347. var disallowObjectUrl = Upload.attrGetter('ngfNoObjectUrl', attr, scope);
  1348. Upload.dataUrl(file, disallowObjectUrl)['finally'](function () {
  1349. $timeout(function () {
  1350. var src = (disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl) || file.$ngfDataUrl;
  1351. if (isBackground) {
  1352. elem.css('background-image', 'url(\'' + (src || '') + '\')');
  1353. } else {
  1354. elem.attr('src', src);
  1355. }
  1356. if (src) {
  1357. elem.removeClass('ng-hide');
  1358. } else {
  1359. elem.addClass('ng-hide');
  1360. }
  1361. });
  1362. });
  1363. }
  1364. $timeout(function () {
  1365. var unwatch = scope.$watch(attr[directiveName], function (file) {
  1366. var size = resizeParams;
  1367. if (directiveName === 'ngfThumbnail') {
  1368. if (!size) {
  1369. size = {
  1370. width: elem[0].naturalWidth || elem[0].clientWidth,
  1371. height: elem[0].naturalHeight || elem[0].clientHeight
  1372. };
  1373. }
  1374. if (size.width === 0 && window.getComputedStyle) {
  1375. var style = getComputedStyle(elem[0]);
  1376. if (style.width && style.width.indexOf('px') > -1 && style.height && style.height.indexOf('px') > -1) {
  1377. size = {
  1378. width: parseInt(style.width.slice(0, -2)),
  1379. height: parseInt(style.height.slice(0, -2))
  1380. };
  1381. }
  1382. }
  1383. }
  1384. if (angular.isString(file)) {
  1385. elem.removeClass('ng-hide');
  1386. if (isBackground) {
  1387. return elem.css('background-image', 'url(\'' + file + '\')');
  1388. } else {
  1389. return elem.attr('src', file);
  1390. }
  1391. }
  1392. if (file && file.type && file.type.search(getTagType(elem[0])) === 0 &&
  1393. (!isBackground || file.type.indexOf('image') === 0)) {
  1394. if (size && Upload.isResizeSupported()) {
  1395. size.resizeIf = function (width, height) {
  1396. return Upload.attrGetter('ngfResizeIf', attr, scope,
  1397. {$width: width, $height: height, $file: file});
  1398. };
  1399. Upload.resize(file, size).then(
  1400. function (f) {
  1401. constructDataUrl(f);
  1402. }, function (e) {
  1403. throw e;
  1404. }
  1405. );
  1406. } else {
  1407. constructDataUrl(file);
  1408. }
  1409. } else {
  1410. elem.addClass('ng-hide');
  1411. }
  1412. });
  1413. scope.$on('$destroy', function () {
  1414. unwatch();
  1415. });
  1416. });
  1417. }
  1418. /** @namespace attr.ngfSrc */
  1419. /** @namespace attr.ngfNoObjectUrl */
  1420. ngFileUpload.directive('ngfSrc', ['Upload', '$timeout', function (Upload, $timeout) {
  1421. return {
  1422. restrict: 'AE',
  1423. link: function (scope, elem, attr) {
  1424. linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfSrc',
  1425. Upload.attrGetter('ngfResize', attr, scope), false);
  1426. }
  1427. };
  1428. }]);
  1429. /** @namespace attr.ngfBackground */
  1430. /** @namespace attr.ngfNoObjectUrl */
  1431. ngFileUpload.directive('ngfBackground', ['Upload', '$timeout', function (Upload, $timeout) {
  1432. return {
  1433. restrict: 'AE',
  1434. link: function (scope, elem, attr) {
  1435. linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfBackground',
  1436. Upload.attrGetter('ngfResize', attr, scope), true);
  1437. }
  1438. };
  1439. }]);
  1440. /** @namespace attr.ngfThumbnail */
  1441. /** @namespace attr.ngfAsBackground */
  1442. /** @namespace attr.ngfSize */
  1443. /** @namespace attr.ngfNoObjectUrl */
  1444. ngFileUpload.directive('ngfThumbnail', ['Upload', '$timeout', function (Upload, $timeout) {
  1445. return {
  1446. restrict: 'AE',
  1447. link: function (scope, elem, attr) {
  1448. var size = Upload.attrGetter('ngfSize', attr, scope);
  1449. linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfThumbnail', size,
  1450. Upload.attrGetter('ngfAsBackground', attr, scope));
  1451. }
  1452. };
  1453. }]);
  1454. ngFileUpload.config(['$compileProvider', function ($compileProvider) {
  1455. if ($compileProvider.imgSrcSanitizationWhitelist) $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|webcal|local|file|data|blob):/);
  1456. if ($compileProvider.aHrefSanitizationWhitelist) $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|webcal|local|file|data|blob):/);
  1457. }]);
  1458. ngFileUpload.filter('ngfDataUrl', ['UploadDataUrl', '$sce', function (UploadDataUrl, $sce) {
  1459. return function (file, disallowObjectUrl, trustedUrl) {
  1460. if (angular.isString(file)) {
  1461. return $sce.trustAsResourceUrl(file);
  1462. }
  1463. var src = file && ((disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl) || file.$ngfDataUrl);
  1464. if (file && !src) {
  1465. if (!file.$ngfDataUrlFilterInProgress && angular.isObject(file)) {
  1466. file.$ngfDataUrlFilterInProgress = true;
  1467. UploadDataUrl.dataUrl(file, disallowObjectUrl);
  1468. }
  1469. return '';
  1470. }
  1471. if (file) delete file.$ngfDataUrlFilterInProgress;
  1472. return (file && src ? (trustedUrl ? $sce.trustAsResourceUrl(src) : src) : file) || '';
  1473. };
  1474. }]);
  1475. })();
  1476. ngFileUpload.service('UploadValidate', ['UploadDataUrl', '$q', '$timeout', function (UploadDataUrl, $q, $timeout) {
  1477. var upload = UploadDataUrl;
  1478. function globStringToRegex(str) {
  1479. var regexp = '', excludes = [];
  1480. if (str.length > 2 && str[0] === '/' && str[str.length - 1] === '/') {
  1481. regexp = str.substring(1, str.length - 1);
  1482. } else {
  1483. var split = str.split(',');
  1484. if (split.length > 1) {
  1485. for (var i = 0; i < split.length; i++) {
  1486. var r = globStringToRegex(split[i]);
  1487. if (r.regexp) {
  1488. regexp += '(' + r.regexp + ')';
  1489. if (i < split.length - 1) {
  1490. regexp += '|';
  1491. }
  1492. } else {
  1493. excludes = excludes.concat(r.excludes);
  1494. }
  1495. }
  1496. } else {
  1497. if (str.indexOf('!') === 0) {
  1498. excludes.push('^((?!' + globStringToRegex(str.substring(1)).regexp + ').)*$');
  1499. } else {
  1500. if (str.indexOf('.') === 0) {
  1501. str = '*' + str;
  1502. }
  1503. regexp = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g'), '\\$&') + '$';
  1504. regexp = regexp.replace(/\\\*/g, '.*').replace(/\\\?/g, '.');
  1505. }
  1506. }
  1507. }
  1508. return {regexp: regexp, excludes: excludes};
  1509. }
  1510. upload.validatePattern = function (file, val) {
  1511. if (!val) {
  1512. return true;
  1513. }
  1514. var pattern = globStringToRegex(val), valid = true;
  1515. if (pattern.regexp && pattern.regexp.length) {
  1516. var regexp = new RegExp(pattern.regexp, 'i');
  1517. valid = (file.type != null && regexp.test(file.type)) ||
  1518. (file.name != null && regexp.test(file.name));
  1519. }
  1520. var len = pattern.excludes.length;
  1521. while (len--) {
  1522. var exclude = new RegExp(pattern.excludes[len], 'i');
  1523. valid = valid && (file.type == null || exclude.test(file.type)) &&
  1524. (file.name == null || exclude.test(file.name));
  1525. }
  1526. return valid;
  1527. };
  1528. upload.ratioToFloat = function (val) {
  1529. var r = val.toString(), xIndex = r.search(/[x:]/i);
  1530. if (xIndex > -1) {
  1531. r = parseFloat(r.substring(0, xIndex)) / parseFloat(r.substring(xIndex + 1));
  1532. } else {
  1533. r = parseFloat(r);
  1534. }
  1535. return r;
  1536. };
  1537. upload.registerModelChangeValidator = function (ngModel, attr, scope) {
  1538. if (ngModel) {
  1539. ngModel.$formatters.push(function (files) {
  1540. if (ngModel.$dirty) {
  1541. var filesArray = files;
  1542. if (files && !angular.isArray(files)) {
  1543. filesArray = [files];
  1544. }
  1545. upload.validate(filesArray, 0, ngModel, attr, scope).then(function () {
  1546. upload.applyModelValidation(ngModel, filesArray);
  1547. });
  1548. }
  1549. return files;
  1550. });
  1551. }
  1552. };
  1553. function markModelAsDirty(ngModel, files) {
  1554. if (files != null && !ngModel.$dirty) {
  1555. if (ngModel.$setDirty) {
  1556. ngModel.$setDirty();
  1557. } else {
  1558. ngModel.$dirty = true;
  1559. }
  1560. }
  1561. }
  1562. upload.applyModelValidation = function (ngModel, files) {
  1563. markModelAsDirty(ngModel, files);
  1564. angular.forEach(ngModel.$ngfValidations, function (validation) {
  1565. ngModel.$setValidity(validation.name, validation.valid);
  1566. });
  1567. };
  1568. upload.getValidationAttr = function (attr, scope, name, validationName, file) {
  1569. var dName = 'ngf' + name[0].toUpperCase() + name.substr(1);
  1570. var val = upload.attrGetter(dName, attr, scope, {$file: file});
  1571. if (val == null) {
  1572. val = upload.attrGetter('ngfValidate', attr, scope, {$file: file});
  1573. if (val) {
  1574. var split = (validationName || name).split('.');
  1575. val = val[split[0]];
  1576. if (split.length > 1) {
  1577. val = val && val[split[1]];
  1578. }
  1579. }
  1580. }
  1581. return val;
  1582. };
  1583. upload.validate = function (files, prevLength, ngModel, attr, scope) {
  1584. ngModel = ngModel || {};
  1585. ngModel.$ngfValidations = ngModel.$ngfValidations || [];
  1586. angular.forEach(ngModel.$ngfValidations, function (v) {
  1587. v.valid = true;
  1588. });
  1589. var attrGetter = function (name, params) {
  1590. return upload.attrGetter(name, attr, scope, params);
  1591. };
  1592. var ignoredErrors = (upload.attrGetter('ngfIgnoreInvalid', attr, scope) || '').split(' ');
  1593. var runAllValidation = upload.attrGetter('ngfRunAllValidations', attr, scope);
  1594. if (files == null || files.length === 0) {
  1595. return upload.emptyPromise({'validFiles': files, 'invalidFiles': []});
  1596. }
  1597. files = files.length === undefined ? [files] : files.slice(0);
  1598. var invalidFiles = [];
  1599. function validateSync(name, validationName, fn) {
  1600. if (files) {
  1601. var i = files.length, valid = null;
  1602. while (i--) {
  1603. var file = files[i];
  1604. if (file) {
  1605. var val = upload.getValidationAttr(attr, scope, name, validationName, file);
  1606. if (val != null) {
  1607. if (!fn(file, val, i)) {
  1608. if (ignoredErrors.indexOf(name) === -1) {
  1609. file.$error = name;
  1610. (file.$errorMessages = (file.$errorMessages || {}))[name] = true;
  1611. file.$errorParam = val;
  1612. if (invalidFiles.indexOf(file) === -1) {
  1613. invalidFiles.push(file);
  1614. }
  1615. if (!runAllValidation) {
  1616. files.splice(i, 1);
  1617. }
  1618. valid = false;
  1619. } else {
  1620. files.splice(i, 1);
  1621. }
  1622. }
  1623. }
  1624. }
  1625. }
  1626. if (valid !== null) {
  1627. ngModel.$ngfValidations.push({name: name, valid: valid});
  1628. }
  1629. }
  1630. }
  1631. validateSync('pattern', null, upload.validatePattern);
  1632. validateSync('minSize', 'size.min', function (file, val) {
  1633. return file.size + 0.1 >= upload.translateScalars(val);
  1634. });
  1635. validateSync('maxSize', 'size.max', function (file, val) {
  1636. return file.size - 0.1 <= upload.translateScalars(val);
  1637. });
  1638. var totalSize = 0;
  1639. validateSync('maxTotalSize', null, function (file, val) {
  1640. totalSize += file.size;
  1641. if (totalSize > upload.translateScalars(val)) {
  1642. files.splice(0, files.length);
  1643. return false;
  1644. }
  1645. return true;
  1646. });
  1647. validateSync('validateFn', null, function (file, r) {
  1648. return r === true || r === null || r === '';
  1649. });
  1650. if (!files.length) {
  1651. return upload.emptyPromise({'validFiles': [], 'invalidFiles': invalidFiles});
  1652. }
  1653. function validateAsync(name, validationName, type, asyncFn, fn) {
  1654. function resolveResult(defer, file, val) {
  1655. function resolveInternal(fn) {
  1656. if (fn()) {
  1657. if (ignoredErrors.indexOf(name) === -1) {
  1658. file.$error = name;
  1659. (file.$errorMessages = (file.$errorMessages || {}))[name] = true;
  1660. file.$errorParam = val;
  1661. if (invalidFiles.indexOf(file) === -1) {
  1662. invalidFiles.push(file);
  1663. }
  1664. if (!runAllValidation) {
  1665. var i = files.indexOf(file);
  1666. if (i > -1) files.splice(i, 1);
  1667. }
  1668. defer.resolve(false);
  1669. } else {
  1670. var j = files.indexOf(file);
  1671. if (j > -1) files.splice(j, 1);
  1672. defer.resolve(true);
  1673. }
  1674. } else {
  1675. defer.resolve(true);
  1676. }
  1677. }
  1678. if (val != null) {
  1679. asyncFn(file, val).then(function (d) {
  1680. resolveInternal(function () {
  1681. return !fn(d, val);
  1682. });
  1683. }, function () {
  1684. resolveInternal(function () {
  1685. return attrGetter('ngfValidateForce', {$file: file});
  1686. });
  1687. });
  1688. } else {
  1689. defer.resolve(true);
  1690. }
  1691. }
  1692. var promises = [upload.emptyPromise(true)];
  1693. if (files) {
  1694. files = files.length === undefined ? [files] : files;
  1695. angular.forEach(files, function (file) {
  1696. var defer = $q.defer();
  1697. promises.push(defer.promise);
  1698. if (type && (file.type == null || file.type.search(type) !== 0)) {
  1699. defer.resolve(true);
  1700. return;
  1701. }
  1702. if (name === 'dimensions' && upload.attrGetter('ngfDimensions', attr) != null) {
  1703. upload.imageDimensions(file).then(function (d) {
  1704. resolveResult(defer, file,
  1705. attrGetter('ngfDimensions', {$file: file, $width: d.width, $height: d.height}));
  1706. }, function () {
  1707. defer.resolve(false);
  1708. });
  1709. } else if (name === 'duration' && upload.attrGetter('ngfDuration', attr) != null) {
  1710. upload.mediaDuration(file).then(function (d) {
  1711. resolveResult(defer, file,
  1712. attrGetter('ngfDuration', {$file: file, $duration: d}));
  1713. }, function () {
  1714. defer.resolve(false);
  1715. });
  1716. } else {
  1717. resolveResult(defer, file,
  1718. upload.getValidationAttr(attr, scope, name, validationName, file));
  1719. }
  1720. });
  1721. }
  1722. var deffer = $q.defer();
  1723. $q.all(promises).then(function (values) {
  1724. var isValid = true;
  1725. for (var i = 0; i < values.length; i++) {
  1726. if (!values[i]) {
  1727. isValid = false;
  1728. break;
  1729. }
  1730. }
  1731. ngModel.$ngfValidations.push({name: name, valid: isValid});
  1732. deffer.resolve(isValid);
  1733. });
  1734. return deffer.promise;
  1735. }
  1736. var deffer = $q.defer();
  1737. var promises = [];
  1738. promises.push(validateAsync('maxHeight', 'height.max', /image/,
  1739. this.imageDimensions, function (d, val) {
  1740. return d.height <= val;
  1741. }));
  1742. promises.push(validateAsync('minHeight', 'height.min', /image/,
  1743. this.imageDimensions, function (d, val) {
  1744. return d.height >= val;
  1745. }));
  1746. promises.push(validateAsync('maxWidth', 'width.max', /image/,
  1747. this.imageDimensions, function (d, val) {
  1748. return d.width <= val;
  1749. }));
  1750. promises.push(validateAsync('minWidth', 'width.min', /image/,
  1751. this.imageDimensions, function (d, val) {
  1752. return d.width >= val;
  1753. }));
  1754. promises.push(validateAsync('dimensions', null, /image/,
  1755. function (file, val) {
  1756. return upload.emptyPromise(val);
  1757. }, function (r) {
  1758. return r;
  1759. }));
  1760. promises.push(validateAsync('ratio', null, /image/,
  1761. this.imageDimensions, function (d, val) {
  1762. var split = val.toString().split(','), valid = false;
  1763. for (var i = 0; i < split.length; i++) {
  1764. if (Math.abs((d.width / d.height) - upload.ratioToFloat(split[i])) < 0.01) {
  1765. valid = true;
  1766. }
  1767. }
  1768. return valid;
  1769. }));
  1770. promises.push(validateAsync('maxRatio', 'ratio.max', /image/,
  1771. this.imageDimensions, function (d, val) {
  1772. return (d.width / d.height) - upload.ratioToFloat(val) < 0.0001;
  1773. }));
  1774. promises.push(validateAsync('minRatio', 'ratio.min', /image/,
  1775. this.imageDimensions, function (d, val) {
  1776. return (d.width / d.height) - upload.ratioToFloat(val) > -0.0001;
  1777. }));
  1778. promises.push(validateAsync('maxDuration', 'duration.max', /audio|video/,
  1779. this.mediaDuration, function (d, val) {
  1780. return d <= upload.translateScalars(val);
  1781. }));
  1782. promises.push(validateAsync('minDuration', 'duration.min', /audio|video/,
  1783. this.mediaDuration, function (d, val) {
  1784. return d >= upload.translateScalars(val);
  1785. }));
  1786. promises.push(validateAsync('duration', null, /audio|video/,
  1787. function (file, val) {
  1788. return upload.emptyPromise(val);
  1789. }, function (r) {
  1790. return r;
  1791. }));
  1792. promises.push(validateAsync('validateAsyncFn', null, null,
  1793. function (file, val) {
  1794. return val;
  1795. }, function (r) {
  1796. return r === true || r === null || r === '';
  1797. }));
  1798. $q.all(promises).then(function () {
  1799. if (runAllValidation) {
  1800. for (var i = 0; i < files.length; i++) {
  1801. var file = files[i];
  1802. if (file.$error) {
  1803. files.splice(i--, 1);
  1804. }
  1805. }
  1806. }
  1807. runAllValidation = false;
  1808. validateSync('maxFiles', null, function (file, val, i) {
  1809. return prevLength + i < val;
  1810. });
  1811. deffer.resolve({'validFiles': files, 'invalidFiles': invalidFiles});
  1812. });
  1813. return deffer.promise;
  1814. };
  1815. upload.imageDimensions = function (file) {
  1816. if (file.$ngfWidth && file.$ngfHeight) {
  1817. var d = $q.defer();
  1818. $timeout(function () {
  1819. d.resolve({width: file.$ngfWidth, height: file.$ngfHeight});
  1820. });
  1821. return d.promise;
  1822. }
  1823. if (file.$ngfDimensionPromise) return file.$ngfDimensionPromise;
  1824. var deferred = $q.defer();
  1825. $timeout(function () {
  1826. if (file.type.indexOf('image') !== 0) {
  1827. deferred.reject('not image');
  1828. return;
  1829. }
  1830. upload.dataUrl(file).then(function (dataUrl) {
  1831. var img = angular.element('<img>').attr('src', dataUrl)
  1832. .css('visibility', 'hidden').css('position', 'fixed')
  1833. .css('max-width', 'none !important').css('max-height', 'none !important');
  1834. function success() {
  1835. var width = img[0].naturalWidth || img[0].clientWidth;
  1836. var height = img[0].naturalHeight || img[0].clientHeight;
  1837. img.remove();
  1838. file.$ngfWidth = width;
  1839. file.$ngfHeight = height;
  1840. deferred.resolve({width: width, height: height});
  1841. }
  1842. function error() {
  1843. img.remove();
  1844. deferred.reject('load error');
  1845. }
  1846. img.on('load', success);
  1847. img.on('error', error);
  1848. var secondsCounter = 0;
  1849. function checkLoadErrorInCaseOfNoCallback() {
  1850. $timeout(function () {
  1851. if (img[0].parentNode) {
  1852. if (img[0].clientWidth) {
  1853. success();
  1854. } else if (secondsCounter++ > 10) {
  1855. error();
  1856. } else {
  1857. checkLoadErrorInCaseOfNoCallback();
  1858. }
  1859. }
  1860. }, 1000);
  1861. }
  1862. checkLoadErrorInCaseOfNoCallback();
  1863. angular.element(document.getElementsByTagName('body')[0]).append(img);
  1864. }, function () {
  1865. deferred.reject('load error');
  1866. });
  1867. });
  1868. file.$ngfDimensionPromise = deferred.promise;
  1869. file.$ngfDimensionPromise['finally'](function () {
  1870. delete file.$ngfDimensionPromise;
  1871. });
  1872. return file.$ngfDimensionPromise;
  1873. };
  1874. upload.mediaDuration = function (file) {
  1875. if (file.$ngfDuration) {
  1876. var d = $q.defer();
  1877. $timeout(function () {
  1878. d.resolve(file.$ngfDuration);
  1879. });
  1880. return d.promise;
  1881. }
  1882. if (file.$ngfDurationPromise) return file.$ngfDurationPromise;
  1883. var deferred = $q.defer();
  1884. $timeout(function () {
  1885. if (file.type.indexOf('audio') !== 0 && file.type.indexOf('video') !== 0) {
  1886. deferred.reject('not media');
  1887. return;
  1888. }
  1889. upload.dataUrl(file).then(function (dataUrl) {
  1890. var el = angular.element(file.type.indexOf('audio') === 0 ? '<audio>' : '<video>')
  1891. .attr('src', dataUrl).css('visibility', 'none').css('position', 'fixed');
  1892. function success() {
  1893. var duration = el[0].duration;
  1894. file.$ngfDuration = duration;
  1895. el.remove();
  1896. deferred.resolve(duration);
  1897. }
  1898. function error() {
  1899. el.remove();
  1900. deferred.reject('load error');
  1901. }
  1902. el.on('loadedmetadata', success);
  1903. el.on('error', error);
  1904. var count = 0;
  1905. function checkLoadError() {
  1906. $timeout(function () {
  1907. if (el[0].parentNode) {
  1908. if (el[0].duration) {
  1909. success();
  1910. } else if (count > 10) {
  1911. error();
  1912. } else {
  1913. checkLoadError();
  1914. }
  1915. }
  1916. }, 1000);
  1917. }
  1918. checkLoadError();
  1919. angular.element(document.body).append(el);
  1920. }, function () {
  1921. deferred.reject('load error');
  1922. });
  1923. });
  1924. file.$ngfDurationPromise = deferred.promise;
  1925. file.$ngfDurationPromise['finally'](function () {
  1926. delete file.$ngfDurationPromise;
  1927. });
  1928. return file.$ngfDurationPromise;
  1929. };
  1930. return upload;
  1931. }
  1932. ]);
  1933. ngFileUpload.service('UploadResize', ['UploadValidate', '$q', function (UploadValidate, $q) {
  1934. var upload = UploadValidate;
  1935. /**
  1936. * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  1937. * images to fit into a certain area.
  1938. * Source: http://stackoverflow.com/a/14731922
  1939. *
  1940. * @param {Number} srcWidth Source area width
  1941. * @param {Number} srcHeight Source area height
  1942. * @param {Number} maxWidth Nestable area maximum available width
  1943. * @param {Number} maxHeight Nestable area maximum available height
  1944. * @return {Object} { width, height }
  1945. */
  1946. var calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight, centerCrop) {
  1947. var ratio = centerCrop ? Math.max(maxWidth / srcWidth, maxHeight / srcHeight) :
  1948. Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
  1949. return {
  1950. width: srcWidth * ratio, height: srcHeight * ratio,
  1951. marginX: srcWidth * ratio - maxWidth, marginY: srcHeight * ratio - maxHeight
  1952. };
  1953. };
  1954. // Extracted from https://github.com/romelgomez/angular-firebase-image-upload/blob/master/app/scripts/fileUpload.js#L89
  1955. var resize = function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
  1956. var deferred = $q.defer();
  1957. var canvasElement = document.createElement('canvas');
  1958. var imageElement = document.createElement('img');
  1959. imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
  1960. document.body.appendChild(imageElement);
  1961. imageElement.onload = function () {
  1962. var imgWidth = imageElement.width, imgHeight = imageElement.height;
  1963. imageElement.parentNode.removeChild(imageElement);
  1964. if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
  1965. deferred.reject('resizeIf');
  1966. return;
  1967. }
  1968. try {
  1969. if (ratio) {
  1970. var ratioFloat = upload.ratioToFloat(ratio);
  1971. var imgRatio = imgWidth / imgHeight;
  1972. if (imgRatio < ratioFloat) {
  1973. width = imgWidth;
  1974. height = width / ratioFloat;
  1975. } else {
  1976. height = imgHeight;
  1977. width = height * ratioFloat;
  1978. }
  1979. }
  1980. if (!width) {
  1981. width = imgWidth;
  1982. }
  1983. if (!height) {
  1984. height = imgHeight;
  1985. }
  1986. var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
  1987. canvasElement.width = Math.min(dimensions.width, width);
  1988. canvasElement.height = Math.min(dimensions.height, height);
  1989. var context = canvasElement.getContext('2d');
  1990. context.drawImage(imageElement,
  1991. Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
  1992. dimensions.width, dimensions.height);
  1993. deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
  1994. } catch (e) {
  1995. deferred.reject(e);
  1996. }
  1997. };
  1998. imageElement.onerror = function () {
  1999. imageElement.parentNode.removeChild(imageElement);
  2000. deferred.reject();
  2001. };
  2002. imageElement.src = imagen;
  2003. return deferred.promise;
  2004. };
  2005. upload.dataUrltoBlob = function (dataurl, name, origSize) {
  2006. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  2007. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  2008. while (n--) {
  2009. u8arr[n] = bstr.charCodeAt(n);
  2010. }
  2011. var blob = new window.Blob([u8arr], {type: mime});
  2012. blob.name = name;
  2013. blob.$ngfOrigSize = origSize;
  2014. return blob;
  2015. };
  2016. upload.isResizeSupported = function () {
  2017. var elem = document.createElement('canvas');
  2018. return window.atob && elem.getContext && elem.getContext('2d') && window.Blob;
  2019. };
  2020. if (upload.isResizeSupported()) {
  2021. // add name getter to the blob constructor prototype
  2022. Object.defineProperty(window.Blob.prototype, 'name', {
  2023. get: function () {
  2024. return this.$ngfName;
  2025. },
  2026. set: function (v) {
  2027. this.$ngfName = v;
  2028. },
  2029. configurable: true
  2030. });
  2031. }
  2032. upload.resize = function (file, options) {
  2033. if (file.type.indexOf('image') !== 0) return upload.emptyPromise(file);
  2034. var deferred = $q.defer();
  2035. upload.dataUrl(file, true).then(function (url) {
  2036. resize(url, options.width, options.height, options.quality, options.type || file.type,
  2037. options.ratio, options.centerCrop, options.resizeIf)
  2038. .then(function (dataUrl) {
  2039. if (file.type === 'image/jpeg' && options.restoreExif !== false) {
  2040. try {
  2041. dataUrl = upload.restoreExif(url, dataUrl);
  2042. } catch (e) {
  2043. setTimeout(function () {throw e;}, 1);
  2044. }
  2045. }
  2046. try {
  2047. var blob = upload.dataUrltoBlob(dataUrl, file.name, file.size);
  2048. deferred.resolve(blob);
  2049. } catch (e) {
  2050. deferred.reject(e);
  2051. }
  2052. }, function (r) {
  2053. if (r === 'resizeIf') {
  2054. deferred.resolve(file);
  2055. }
  2056. deferred.reject(r);
  2057. });
  2058. }, function (e) {
  2059. deferred.reject(e);
  2060. });
  2061. return deferred.promise;
  2062. };
  2063. return upload;
  2064. }]);
  2065. (function () {
  2066. ngFileUpload.directive('ngfDrop', ['$parse', '$timeout', '$window', 'Upload', '$http', '$q',
  2067. function ($parse, $timeout, $window, Upload, $http, $q) {
  2068. return {
  2069. restrict: 'AEC',
  2070. require: '?ngModel',
  2071. link: function (scope, elem, attr, ngModel) {
  2072. linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $window, Upload, $http, $q);
  2073. }
  2074. };
  2075. }]);
  2076. ngFileUpload.directive('ngfNoFileDrop', function () {
  2077. return function (scope, elem) {
  2078. if (dropAvailable()) elem.css('display', 'none');
  2079. };
  2080. });
  2081. ngFileUpload.directive('ngfDropAvailable', ['$parse', '$timeout', 'Upload', function ($parse, $timeout, Upload) {
  2082. return function (scope, elem, attr) {
  2083. if (dropAvailable()) {
  2084. var model = $parse(Upload.attrGetter('ngfDropAvailable', attr));
  2085. $timeout(function () {
  2086. model(scope);
  2087. if (model.assign) {
  2088. model.assign(scope, true);
  2089. }
  2090. });
  2091. }
  2092. };
  2093. }]);
  2094. function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $window, upload, $http, $q) {
  2095. var available = dropAvailable();
  2096. var attrGetter = function (name, scope, params) {
  2097. return upload.attrGetter(name, attr, scope, params);
  2098. };
  2099. if (attrGetter('dropAvailable')) {
  2100. $timeout(function () {
  2101. if (scope[attrGetter('dropAvailable')]) {
  2102. scope[attrGetter('dropAvailable')].value = available;
  2103. } else {
  2104. scope[attrGetter('dropAvailable')] = available;
  2105. }
  2106. });
  2107. }
  2108. if (!available) {
  2109. if (attrGetter('ngfHideOnDropNotAvailable', scope) === true) {
  2110. elem.css('display', 'none');
  2111. }
  2112. return;
  2113. }
  2114. function isDisabled() {
  2115. return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
  2116. }
  2117. if (attrGetter('ngfSelect') == null) {
  2118. upload.registerModelChangeValidator(ngModel, attr, scope);
  2119. }
  2120. var leaveTimeout = null;
  2121. var stopPropagation = $parse(attrGetter('ngfStopPropagation'));
  2122. var dragOverDelay = 1;
  2123. var actualDragOverClass;
  2124. elem[0].addEventListener('dragover', function (evt) {
  2125. if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
  2126. evt.preventDefault();
  2127. if (stopPropagation(scope)) evt.stopPropagation();
  2128. // handling dragover events from the Chrome download bar
  2129. if (navigator.userAgent.indexOf('Chrome') > -1) {
  2130. var b = evt.dataTransfer.effectAllowed;
  2131. evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy';
  2132. }
  2133. $timeout.cancel(leaveTimeout);
  2134. if (!actualDragOverClass) {
  2135. actualDragOverClass = 'C';
  2136. calculateDragOverClass(scope, attr, evt, function (clazz) {
  2137. actualDragOverClass = clazz;
  2138. elem.addClass(actualDragOverClass);
  2139. attrGetter('ngfDrag', scope, {$isDragging: true, $class: actualDragOverClass, $event: evt});
  2140. });
  2141. }
  2142. }, false);
  2143. elem[0].addEventListener('dragenter', function (evt) {
  2144. if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
  2145. evt.preventDefault();
  2146. if (stopPropagation(scope)) evt.stopPropagation();
  2147. }, false);
  2148. elem[0].addEventListener('dragleave', function (evt) {
  2149. if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
  2150. evt.preventDefault();
  2151. if (stopPropagation(scope)) evt.stopPropagation();
  2152. leaveTimeout = $timeout(function () {
  2153. if (actualDragOverClass) elem.removeClass(actualDragOverClass);
  2154. actualDragOverClass = null;
  2155. attrGetter('ngfDrag', scope, {$isDragging: false, $event: evt});
  2156. }, dragOverDelay || 100);
  2157. }, false);
  2158. elem[0].addEventListener('drop', function (evt) {
  2159. if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
  2160. evt.preventDefault();
  2161. if (stopPropagation(scope)) evt.stopPropagation();
  2162. if (actualDragOverClass) elem.removeClass(actualDragOverClass);
  2163. actualDragOverClass = null;
  2164. extractFilesAndUpdateModel(evt.dataTransfer, evt, 'dropUrl');
  2165. }, false);
  2166. elem[0].addEventListener('paste', function (evt) {
  2167. if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
  2168. attrGetter('ngfEnableFirefoxPaste', scope)) {
  2169. evt.preventDefault();
  2170. }
  2171. if (isDisabled() || !upload.shouldUpdateOn('paste', attr, scope)) return;
  2172. extractFilesAndUpdateModel(evt.clipboardData || evt.originalEvent.clipboardData, evt, 'pasteUrl');
  2173. }, false);
  2174. if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
  2175. attrGetter('ngfEnableFirefoxPaste', scope)) {
  2176. elem.attr('contenteditable', true);
  2177. elem.on('keypress', function (e) {
  2178. if (!e.metaKey && !e.ctrlKey) {
  2179. e.preventDefault();
  2180. }
  2181. });
  2182. }
  2183. function extractFilesAndUpdateModel(source, evt, updateOnType) {
  2184. if (!source) return;
  2185. // html needs to be calculated on the same process otherwise the data will be wiped
  2186. // after promise resolve or setTimeout.
  2187. var html;
  2188. try {
  2189. html = source && source.getData && source.getData('text/html');
  2190. } catch (e) {/* Fix IE11 that throw error calling getData */
  2191. }
  2192. extractFiles(source.items, source.files, attrGetter('ngfAllowDir', scope) !== false,
  2193. attrGetter('multiple') || attrGetter('ngfMultiple', scope)).then(function (files) {
  2194. if (files.length) {
  2195. updateModel(files, evt);
  2196. } else {
  2197. extractFilesFromHtml(updateOnType, html).then(function (files) {
  2198. updateModel(files, evt);
  2199. });
  2200. }
  2201. });
  2202. }
  2203. function updateModel(files, evt) {
  2204. upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
  2205. }
  2206. function extractFilesFromHtml(updateOn, html) {
  2207. if (!upload.shouldUpdateOn(updateOn, attr, scope) || typeof html !== 'string') return upload.rejectPromise([]);
  2208. var urls = [];
  2209. html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) {
  2210. urls.push(src);
  2211. });
  2212. var promises = [], files = [];
  2213. if (urls.length) {
  2214. angular.forEach(urls, function (url) {
  2215. promises.push(upload.urlToBlob(url).then(function (blob) {
  2216. files.push(blob);
  2217. }));
  2218. });
  2219. var defer = $q.defer();
  2220. $q.all(promises).then(function () {
  2221. defer.resolve(files);
  2222. }, function (e) {
  2223. defer.reject(e);
  2224. });
  2225. return defer.promise;
  2226. }
  2227. return upload.emptyPromise();
  2228. }
  2229. function calculateDragOverClass(scope, attr, evt, callback) {
  2230. var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover';
  2231. if (angular.isString(obj)) {
  2232. dClass = obj;
  2233. } else if (obj) {
  2234. if (obj.delay) dragOverDelay = obj.delay;
  2235. if (obj.accept || obj.reject) {
  2236. var items = evt.dataTransfer.items;
  2237. if (items == null || !items.length) {
  2238. dClass = obj.accept;
  2239. } else {
  2240. var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt});
  2241. var len = items.length;
  2242. while (len--) {
  2243. if (!upload.validatePattern(items[len], pattern)) {
  2244. dClass = obj.reject;
  2245. break;
  2246. } else {
  2247. dClass = obj.accept;
  2248. }
  2249. }
  2250. }
  2251. }
  2252. }
  2253. callback(dClass);
  2254. }
  2255. function extractFiles(items, fileList, allowDir, multiple) {
  2256. var maxFiles = upload.getValidationAttr(attr, scope, 'maxFiles');
  2257. if (maxFiles == null) {
  2258. maxFiles = Number.MAX_VALUE;
  2259. }
  2260. var maxTotalSize = upload.getValidationAttr(attr, scope, 'maxTotalSize');
  2261. if (maxTotalSize == null) {
  2262. maxTotalSize = Number.MAX_VALUE;
  2263. }
  2264. var includeDir = attrGetter('ngfIncludeDir', scope);
  2265. var files = [], totalSize = 0;
  2266. function traverseFileTree(entry, path) {
  2267. var defer = $q.defer();
  2268. if (entry != null) {
  2269. if (entry.isDirectory) {
  2270. var promises = [upload.emptyPromise()];
  2271. if (includeDir) {
  2272. var file = {type: 'directory'};
  2273. file.name = file.path = (path || '') + entry.name;
  2274. files.push(file);
  2275. }
  2276. var dirReader = entry.createReader();
  2277. var entries = [];
  2278. var readEntries = function () {
  2279. dirReader.readEntries(function (results) {
  2280. try {
  2281. if (!results.length) {
  2282. angular.forEach(entries.slice(0), function (e) {
  2283. if (files.length <= maxFiles && totalSize <= maxTotalSize) {
  2284. promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
  2285. }
  2286. });
  2287. $q.all(promises).then(function () {
  2288. defer.resolve();
  2289. }, function (e) {
  2290. defer.reject(e);
  2291. });
  2292. } else {
  2293. entries = entries.concat(Array.prototype.slice.call(results || [], 0));
  2294. readEntries();
  2295. }
  2296. } catch (e) {
  2297. defer.reject(e);
  2298. }
  2299. }, function (e) {
  2300. defer.reject(e);
  2301. });
  2302. };
  2303. readEntries();
  2304. } else {
  2305. entry.file(function (file) {
  2306. try {
  2307. file.path = (path ? path : '') + file.name;
  2308. if (includeDir) {
  2309. file = upload.rename(file, file.path);
  2310. }
  2311. files.push(file);
  2312. totalSize += file.size;
  2313. defer.resolve();
  2314. } catch (e) {
  2315. defer.reject(e);
  2316. }
  2317. }, function (e) {
  2318. defer.reject(e);
  2319. });
  2320. }
  2321. }
  2322. return defer.promise;
  2323. }
  2324. var promises = [upload.emptyPromise()];
  2325. if (items && items.length > 0 && $window.location.protocol !== 'file:') {
  2326. for (var i = 0; i < items.length; i++) {
  2327. if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
  2328. var entry = items[i].webkitGetAsEntry();
  2329. if (entry.isDirectory && !allowDir) {
  2330. continue;
  2331. }
  2332. if (entry != null) {
  2333. promises.push(traverseFileTree(entry));
  2334. }
  2335. } else {
  2336. var f = items[i].getAsFile();
  2337. if (f != null) {
  2338. files.push(f);
  2339. totalSize += f.size;
  2340. }
  2341. }
  2342. if (files.length > maxFiles || totalSize > maxTotalSize ||
  2343. (!multiple && files.length > 0)) break;
  2344. }
  2345. } else {
  2346. if (fileList != null) {
  2347. for (var j = 0; j < fileList.length; j++) {
  2348. var file = fileList.item(j);
  2349. if (file.type || file.size > 0) {
  2350. files.push(file);
  2351. totalSize += file.size;
  2352. }
  2353. if (files.length > maxFiles || totalSize > maxTotalSize ||
  2354. (!multiple && files.length > 0)) break;
  2355. }
  2356. }
  2357. }
  2358. var defer = $q.defer();
  2359. $q.all(promises).then(function () {
  2360. if (!multiple && !includeDir && files.length) {
  2361. var i = 0;
  2362. while (files[i] && files[i].type === 'directory') i++;
  2363. defer.resolve([files[i]]);
  2364. } else {
  2365. defer.resolve(files);
  2366. }
  2367. }, function (e) {
  2368. defer.reject(e);
  2369. });
  2370. return defer.promise;
  2371. }
  2372. }
  2373. function dropAvailable() {
  2374. var div = document.createElement('div');
  2375. return ('draggable' in div) && ('ondrop' in div) && !/Edge\/12./i.test(navigator.userAgent);
  2376. }
  2377. })();
  2378. // customized version of https://github.com/exif-js/exif-js
  2379. ngFileUpload.service('UploadExif', ['UploadResize', '$q', function (UploadResize, $q) {
  2380. var upload = UploadResize;
  2381. upload.isExifSupported = function () {
  2382. return window.FileReader && new FileReader().readAsArrayBuffer && upload.isResizeSupported();
  2383. };
  2384. function applyTransform(ctx, orientation, width, height) {
  2385. switch (orientation) {
  2386. case 2:
  2387. return ctx.transform(-1, 0, 0, 1, width, 0);
  2388. case 3:
  2389. return ctx.transform(-1, 0, 0, -1, width, height);
  2390. case 4:
  2391. return ctx.transform(1, 0, 0, -1, 0, height);
  2392. case 5:
  2393. return ctx.transform(0, 1, 1, 0, 0, 0);
  2394. case 6:
  2395. return ctx.transform(0, 1, -1, 0, height, 0);
  2396. case 7:
  2397. return ctx.transform(0, -1, -1, 0, height, width);
  2398. case 8:
  2399. return ctx.transform(0, -1, 1, 0, 0, width);
  2400. }
  2401. }
  2402. upload.readOrientation = function (file) {
  2403. var defer = $q.defer();
  2404. var reader = new FileReader();
  2405. var slicedFile = file.slice ? file.slice(0, 64 * 1024) : file;
  2406. reader.readAsArrayBuffer(slicedFile);
  2407. reader.onerror = function (e) {
  2408. return defer.reject(e);
  2409. };
  2410. reader.onload = function (e) {
  2411. var result = {orientation: 1};
  2412. var view = new DataView(this.result);
  2413. if (view.getUint16(0, false) !== 0xFFD8) return defer.resolve(result);
  2414. var length = view.byteLength,
  2415. offset = 2;
  2416. while (offset < length) {
  2417. var marker = view.getUint16(offset, false);
  2418. offset += 2;
  2419. if (marker === 0xFFE1) {
  2420. if (view.getUint32(offset += 2, false) !== 0x45786966) return defer.resolve(result);
  2421. var little = view.getUint16(offset += 6, false) === 0x4949;
  2422. offset += view.getUint32(offset + 4, little);
  2423. var tags = view.getUint16(offset, little);
  2424. offset += 2;
  2425. for (var i = 0; i < tags; i++)
  2426. if (view.getUint16(offset + (i * 12), little) === 0x0112) {
  2427. var orientation = view.getUint16(offset + (i * 12) + 8, little);
  2428. if (orientation >= 2 && orientation <= 8) {
  2429. view.setUint16(offset + (i * 12) + 8, 1, little);
  2430. result.fixedArrayBuffer = e.target.result;
  2431. }
  2432. result.orientation = orientation;
  2433. return defer.resolve(result);
  2434. }
  2435. } else if ((marker & 0xFF00) !== 0xFF00) break;
  2436. else offset += view.getUint16(offset, false);
  2437. }
  2438. return defer.resolve(result);
  2439. };
  2440. return defer.promise;
  2441. };
  2442. function arrayBufferToBase64(buffer) {
  2443. var binary = '';
  2444. var bytes = new Uint8Array(buffer);
  2445. var len = bytes.byteLength;
  2446. for (var i = 0; i < len; i++) {
  2447. binary += String.fromCharCode(bytes[i]);
  2448. }
  2449. return window.btoa(binary);
  2450. }
  2451. upload.applyExifRotation = function (file) {
  2452. if (file.type.indexOf('image/jpeg') !== 0) {
  2453. return upload.emptyPromise(file);
  2454. }
  2455. var deferred = $q.defer();
  2456. upload.readOrientation(file).then(function (result) {
  2457. if (result.orientation < 2 || result.orientation > 8) {
  2458. return deferred.resolve(file);
  2459. }
  2460. upload.dataUrl(file, true).then(function (url) {
  2461. var canvas = document.createElement('canvas');
  2462. var img = document.createElement('img');
  2463. img.onload = function () {
  2464. try {
  2465. canvas.width = result.orientation > 4 ? img.height : img.width;
  2466. canvas.height = result.orientation > 4 ? img.width : img.height;
  2467. var ctx = canvas.getContext('2d');
  2468. applyTransform(ctx, result.orientation, img.width, img.height);
  2469. ctx.drawImage(img, 0, 0);
  2470. var dataUrl = canvas.toDataURL(file.type || 'image/WebP', 0.934);
  2471. dataUrl = upload.restoreExif(arrayBufferToBase64(result.fixedArrayBuffer), dataUrl);
  2472. var blob = upload.dataUrltoBlob(dataUrl, file.name);
  2473. deferred.resolve(blob);
  2474. } catch (e) {
  2475. return deferred.reject(e);
  2476. }
  2477. };
  2478. img.onerror = function () {
  2479. deferred.reject();
  2480. };
  2481. img.src = url;
  2482. }, function (e) {
  2483. deferred.reject(e);
  2484. });
  2485. }, function (e) {
  2486. deferred.reject(e);
  2487. });
  2488. return deferred.promise;
  2489. };
  2490. upload.restoreExif = function (orig, resized) {
  2491. var ExifRestorer = {};
  2492. ExifRestorer.KEY_STR = 'ABCDEFGHIJKLMNOP' +
  2493. 'QRSTUVWXYZabcdef' +
  2494. 'ghijklmnopqrstuv' +
  2495. 'wxyz0123456789+/' +
  2496. '=';
  2497. ExifRestorer.encode64 = function (input) {
  2498. var output = '',
  2499. chr1, chr2, chr3 = '',
  2500. enc1, enc2, enc3, enc4 = '',
  2501. i = 0;
  2502. do {
  2503. chr1 = input[i++];
  2504. chr2 = input[i++];
  2505. chr3 = input[i++];
  2506. enc1 = chr1 >> 2;
  2507. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  2508. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  2509. enc4 = chr3 & 63;
  2510. if (isNaN(chr2)) {
  2511. enc3 = enc4 = 64;
  2512. } else if (isNaN(chr3)) {
  2513. enc4 = 64;
  2514. }
  2515. output = output +
  2516. this.KEY_STR.charAt(enc1) +
  2517. this.KEY_STR.charAt(enc2) +
  2518. this.KEY_STR.charAt(enc3) +
  2519. this.KEY_STR.charAt(enc4);
  2520. chr1 = chr2 = chr3 = '';
  2521. enc1 = enc2 = enc3 = enc4 = '';
  2522. } while (i < input.length);
  2523. return output;
  2524. };
  2525. ExifRestorer.restore = function (origFileBase64, resizedFileBase64) {
  2526. if (origFileBase64.match('data:image/jpeg;base64,')) {
  2527. origFileBase64 = origFileBase64.replace('data:image/jpeg;base64,', '');
  2528. }
  2529. var rawImage = this.decode64(origFileBase64);
  2530. var segments = this.slice2Segments(rawImage);
  2531. var image = this.exifManipulation(resizedFileBase64, segments);
  2532. return 'data:image/jpeg;base64,' + this.encode64(image);
  2533. };
  2534. ExifRestorer.exifManipulation = function (resizedFileBase64, segments) {
  2535. var exifArray = this.getExifArray(segments),
  2536. newImageArray = this.insertExif(resizedFileBase64, exifArray);
  2537. return new Uint8Array(newImageArray);
  2538. };
  2539. ExifRestorer.getExifArray = function (segments) {
  2540. var seg;
  2541. for (var x = 0; x < segments.length; x++) {
  2542. seg = segments[x];
  2543. if (seg[0] === 255 & seg[1] === 225) //(ff e1)
  2544. {
  2545. return seg;
  2546. }
  2547. }
  2548. return [];
  2549. };
  2550. ExifRestorer.insertExif = function (resizedFileBase64, exifArray) {
  2551. var imageData = resizedFileBase64.replace('data:image/jpeg;base64,', ''),
  2552. buf = this.decode64(imageData),
  2553. separatePoint = buf.indexOf(255, 3),
  2554. mae = buf.slice(0, separatePoint),
  2555. ato = buf.slice(separatePoint),
  2556. array = mae;
  2557. array = array.concat(exifArray);
  2558. array = array.concat(ato);
  2559. return array;
  2560. };
  2561. ExifRestorer.slice2Segments = function (rawImageArray) {
  2562. var head = 0,
  2563. segments = [];
  2564. while (1) {
  2565. if (rawImageArray[head] === 255 & rawImageArray[head + 1] === 218) {
  2566. break;
  2567. }
  2568. if (rawImageArray[head] === 255 & rawImageArray[head + 1] === 216) {
  2569. head += 2;
  2570. }
  2571. else {
  2572. var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3],
  2573. endPoint = head + length + 2,
  2574. seg = rawImageArray.slice(head, endPoint);
  2575. segments.push(seg);
  2576. head = endPoint;
  2577. }
  2578. if (head > rawImageArray.length) {
  2579. break;
  2580. }
  2581. }
  2582. return segments;
  2583. };
  2584. ExifRestorer.decode64 = function (input) {
  2585. var chr1, chr2, chr3 = '',
  2586. enc1, enc2, enc3, enc4 = '',
  2587. i = 0,
  2588. buf = [];
  2589. // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  2590. var base64test = /[^A-Za-z0-9\+\/\=]/g;
  2591. if (base64test.exec(input)) {
  2592. console.log('There were invalid base64 characters in the input text.\n' +
  2593. 'Valid base64 characters are A-Z, a-z, 0-9, ' + ', ' / ',and "="\n' +
  2594. 'Expect errors in decoding.');
  2595. }
  2596. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  2597. do {
  2598. enc1 = this.KEY_STR.indexOf(input.charAt(i++));
  2599. enc2 = this.KEY_STR.indexOf(input.charAt(i++));
  2600. enc3 = this.KEY_STR.indexOf(input.charAt(i++));
  2601. enc4 = this.KEY_STR.indexOf(input.charAt(i++));
  2602. chr1 = (enc1 << 2) | (enc2 >> 4);
  2603. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  2604. chr3 = ((enc3 & 3) << 6) | enc4;
  2605. buf.push(chr1);
  2606. if (enc3 !== 64) {
  2607. buf.push(chr2);
  2608. }
  2609. if (enc4 !== 64) {
  2610. buf.push(chr3);
  2611. }
  2612. chr1 = chr2 = chr3 = '';
  2613. enc1 = enc2 = enc3 = enc4 = '';
  2614. } while (i < input.length);
  2615. return buf;
  2616. };
  2617. return ExifRestorer.restore(orig, resized); //<= EXIF
  2618. };
  2619. return upload;
  2620. }]);