ng-file-upload.js 80 KB

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