jquery.fileupload-angular.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * jQuery File Upload AngularJS Plugin
  3. * https://github.com/blueimp/jQuery-File-Upload
  4. *
  5. * Copyright 2013, Sebastian Tschan
  6. * https://blueimp.net
  7. *
  8. * Licensed under the MIT license:
  9. * https://opensource.org/licenses/MIT
  10. */
  11. /* jshint nomen:false */
  12. /* global define, angular, require */
  13. ;(function (factory) {
  14. 'use strict';
  15. if (typeof define === 'function' && define.amd) {
  16. // Register as an anonymous AMD module:
  17. define([
  18. 'jquery',
  19. 'angular',
  20. './jquery.fileupload-image',
  21. './jquery.fileupload-audio',
  22. './jquery.fileupload-video',
  23. './jquery.fileupload-validate'
  24. ], factory);
  25. } else if (typeof exports === 'object') {
  26. // Node/CommonJS:
  27. factory(
  28. require('jquery'),
  29. require('angular'),
  30. require('./jquery.fileupload-image'),
  31. require('./jquery.fileupload-audio'),
  32. require('./jquery.fileupload-video'),
  33. require('./jquery.fileupload-validate')
  34. );
  35. } else {
  36. factory();
  37. }
  38. }(function () {
  39. 'use strict';
  40. angular.module('blueimp.fileupload', [])
  41. // The fileUpload service provides configuration options
  42. // for the fileUpload directive and default handlers for
  43. // File Upload events:
  44. .provider('fileUpload', function () {
  45. var scopeEvalAsync = function (expression) {
  46. var scope = angular.element(this)
  47. .fileupload('option', 'scope');
  48. // Schedule a new $digest cycle if not already inside of one
  49. // and evaluate the given expression:
  50. scope.$evalAsync(expression);
  51. },
  52. addFileMethods = function (scope, data) {
  53. var files = data.files,
  54. file = files[0];
  55. angular.forEach(files, function (file, index) {
  56. file._index = index;
  57. file.$state = function () {
  58. return data.state();
  59. };
  60. file.$processing = function () {
  61. return data.processing();
  62. };
  63. file.$progress = function () {
  64. return data.progress();
  65. };
  66. file.$response = function () {
  67. return data.response();
  68. };
  69. });
  70. file.$submit = function () {
  71. if (!file.error) {
  72. return data.submit();
  73. }
  74. };
  75. file.$cancel = function () {
  76. return data.abort();
  77. };
  78. },
  79. $config;
  80. $config = this.defaults = {
  81. handleResponse: function (e, data) {
  82. var files = data.result && data.result.files;
  83. if (files) {
  84. data.scope.replace(data.files, files);
  85. } else if (data.errorThrown ||
  86. data.textStatus === 'error') {
  87. data.files[0].error = data.errorThrown ||
  88. data.textStatus;
  89. }
  90. },
  91. add: function (e, data) {
  92. if (e.isDefaultPrevented()) {
  93. return false;
  94. }
  95. var scope = data.scope,
  96. filesCopy = [];
  97. angular.forEach(data.files, function (file) {
  98. filesCopy.push(file);
  99. });
  100. scope.$parent.$applyAsync(function () {
  101. addFileMethods(scope, data);
  102. var method = scope.option('prependFiles') ?
  103. 'unshift' : 'push';
  104. Array.prototype[method].apply(scope.queue, data.files);
  105. });
  106. data.process(function () {
  107. return scope.process(data);
  108. }).always(function () {
  109. scope.$parent.$applyAsync(function () {
  110. addFileMethods(scope, data);
  111. scope.replace(filesCopy, data.files);
  112. });
  113. }).then(function () {
  114. if ((scope.option('autoUpload') ||
  115. data.autoUpload) &&
  116. data.autoUpload !== false) {
  117. data.submit();
  118. }
  119. });
  120. },
  121. done: function (e, data) {
  122. if (e.isDefaultPrevented()) {
  123. return false;
  124. }
  125. var that = this;
  126. data.scope.$apply(function () {
  127. data.handleResponse.call(that, e, data);
  128. });
  129. },
  130. fail: function (e, data) {
  131. if (e.isDefaultPrevented()) {
  132. return false;
  133. }
  134. var that = this,
  135. scope = data.scope;
  136. if (data.errorThrown === 'abort') {
  137. scope.clear(data.files);
  138. return;
  139. }
  140. scope.$apply(function () {
  141. data.handleResponse.call(that, e, data);
  142. });
  143. },
  144. stop: scopeEvalAsync,
  145. processstart: scopeEvalAsync,
  146. processstop: scopeEvalAsync,
  147. getNumberOfFiles: function () {
  148. var scope = this.scope;
  149. return scope.queue.length - scope.processing();
  150. },
  151. dataType: 'json',
  152. autoUpload: false
  153. };
  154. this.$get = [
  155. function () {
  156. return {
  157. defaults: $config
  158. };
  159. }
  160. ];
  161. })
  162. // Format byte numbers to readable presentations:
  163. .provider('formatFileSizeFilter', function () {
  164. var $config = {
  165. // Byte units following the IEC format
  166. // http://en.wikipedia.org/wiki/Kilobyte
  167. units: [
  168. {size: 1000000000, suffix: ' GB'},
  169. {size: 1000000, suffix: ' MB'},
  170. {size: 1000, suffix: ' KB'}
  171. ]
  172. };
  173. this.defaults = $config;
  174. this.$get = function () {
  175. return function (bytes) {
  176. if (!angular.isNumber(bytes)) {
  177. return '';
  178. }
  179. var unit = true,
  180. i = 0,
  181. prefix,
  182. suffix;
  183. while (unit) {
  184. unit = $config.units[i];
  185. prefix = unit.prefix || '';
  186. suffix = unit.suffix || '';
  187. if (i === $config.units.length - 1 || bytes >= unit.size) {
  188. return prefix + (bytes / unit.size).toFixed(2) + suffix;
  189. }
  190. i += 1;
  191. }
  192. };
  193. };
  194. })
  195. // The FileUploadController initializes the fileupload widget and
  196. // provides scope methods to control the File Upload functionality:
  197. .controller('FileUploadController', [
  198. '$scope', '$element', '$attrs', '$window', 'fileUpload','$q',
  199. function ($scope, $element, $attrs, $window, fileUpload, $q) {
  200. var uploadMethods = {
  201. progress: function () {
  202. return $element.fileupload('progress');
  203. },
  204. active: function () {
  205. return $element.fileupload('active');
  206. },
  207. option: function (option, data) {
  208. if (arguments.length === 1) {
  209. return $element.fileupload('option', option);
  210. }
  211. $element.fileupload('option', option, data);
  212. },
  213. add: function (data) {
  214. return $element.fileupload('add', data);
  215. },
  216. send: function (data) {
  217. return $element.fileupload('send', data);
  218. },
  219. process: function (data) {
  220. return $element.fileupload('process', data);
  221. },
  222. processing: function (data) {
  223. return $element.fileupload('processing', data);
  224. }
  225. };
  226. $scope.disabled = !$window.jQuery.support.fileInput;
  227. $scope.queue = $scope.queue || [];
  228. $scope.clear = function (files) {
  229. var queue = this.queue,
  230. i = queue.length,
  231. file = files,
  232. length = 1;
  233. if (angular.isArray(files)) {
  234. file = files[0];
  235. length = files.length;
  236. }
  237. while (i) {
  238. i -= 1;
  239. if (queue[i] === file) {
  240. return queue.splice(i, length);
  241. }
  242. }
  243. };
  244. $scope.replace = function (oldFiles, newFiles) {
  245. var queue = this.queue,
  246. file = oldFiles[0],
  247. i,
  248. j;
  249. for (i = 0; i < queue.length; i += 1) {
  250. if (queue[i] === file) {
  251. for (j = 0; j < newFiles.length; j += 1) {
  252. queue[i + j] = newFiles[j];
  253. }
  254. return;
  255. }
  256. }
  257. };
  258. $scope.applyOnQueue = function (method) {
  259. var list = this.queue.slice(0),
  260. i,
  261. file,
  262. promises = [];
  263. for (i = 0; i < list.length; i += 1) {
  264. file = list[i];
  265. if (file[method]) {
  266. promises.push(file[method]());
  267. }
  268. }
  269. return $q.all(promises);
  270. };
  271. $scope.submit = function () {
  272. return this.applyOnQueue('$submit');
  273. };
  274. $scope.cancel = function () {
  275. return this.applyOnQueue('$cancel');
  276. };
  277. // Add upload methods to the scope:
  278. angular.extend($scope, uploadMethods);
  279. // The fileupload widget will initialize with
  280. // the options provided via "data-"-parameters,
  281. // as well as those given via options object:
  282. $element.fileupload(angular.extend(
  283. {scope: $scope},
  284. fileUpload.defaults
  285. )).on('fileuploadadd', function (e, data) {
  286. data.scope = $scope;
  287. }).on('fileuploadfail', function (e, data) {
  288. if (data.errorThrown === 'abort') {
  289. return;
  290. }
  291. if (data.dataType &&
  292. data.dataType.indexOf('json') === data.dataType.length - 4) {
  293. try {
  294. data.result = angular.fromJson(data.jqXHR.responseText);
  295. } catch (ignore) {}
  296. }
  297. }).on([
  298. 'fileuploadadd',
  299. 'fileuploadsubmit',
  300. 'fileuploadsend',
  301. 'fileuploaddone',
  302. 'fileuploadfail',
  303. 'fileuploadalways',
  304. 'fileuploadprogress',
  305. 'fileuploadprogressall',
  306. 'fileuploadstart',
  307. 'fileuploadstop',
  308. 'fileuploadchange',
  309. 'fileuploadpaste',
  310. 'fileuploaddrop',
  311. 'fileuploaddragover',
  312. 'fileuploadchunksend',
  313. 'fileuploadchunkdone',
  314. 'fileuploadchunkfail',
  315. 'fileuploadchunkalways',
  316. 'fileuploadprocessstart',
  317. 'fileuploadprocess',
  318. 'fileuploadprocessdone',
  319. 'fileuploadprocessfail',
  320. 'fileuploadprocessalways',
  321. 'fileuploadprocessstop'
  322. ].join(' '), function (e, data) {
  323. $scope.$parent.$applyAsync(function () {
  324. if ($scope.$emit(e.type, data).defaultPrevented) {
  325. e.preventDefault();
  326. }
  327. });
  328. }).on('remove', function () {
  329. // Remove upload methods from the scope,
  330. // when the widget is removed:
  331. var method;
  332. for (method in uploadMethods) {
  333. if (uploadMethods.hasOwnProperty(method)) {
  334. delete $scope[method];
  335. }
  336. }
  337. });
  338. // Observe option changes:
  339. $scope.$watch(
  340. $attrs.fileUpload,
  341. function (newOptions) {
  342. if (newOptions) {
  343. $element.fileupload('option', newOptions);
  344. }
  345. }
  346. );
  347. }
  348. ])
  349. // Provide File Upload progress feedback:
  350. .controller('FileUploadProgressController', [
  351. '$scope', '$attrs', '$parse',
  352. function ($scope, $attrs, $parse) {
  353. var fn = $parse($attrs.fileUploadProgress),
  354. update = function () {
  355. var progress = fn($scope);
  356. if (!progress || !progress.total) {
  357. return;
  358. }
  359. $scope.num = Math.floor(
  360. progress.loaded / progress.total * 100
  361. );
  362. };
  363. update();
  364. $scope.$watch(
  365. $attrs.fileUploadProgress + '.loaded',
  366. function (newValue, oldValue) {
  367. if (newValue !== oldValue) {
  368. update();
  369. }
  370. }
  371. );
  372. }
  373. ])
  374. // Display File Upload previews:
  375. .controller('FileUploadPreviewController', [
  376. '$scope', '$element', '$attrs',
  377. function ($scope, $element, $attrs) {
  378. $scope.$watch(
  379. $attrs.fileUploadPreview + '.preview',
  380. function (preview) {
  381. $element.empty();
  382. if (preview) {
  383. $element.append(preview);
  384. }
  385. }
  386. );
  387. }
  388. ])
  389. .directive('fileUpload', function () {
  390. return {
  391. controller: 'FileUploadController',
  392. scope: true
  393. };
  394. })
  395. .directive('fileUploadProgress', function () {
  396. return {
  397. controller: 'FileUploadProgressController',
  398. scope: true
  399. };
  400. })
  401. .directive('fileUploadPreview', function () {
  402. return {
  403. controller: 'FileUploadPreviewController'
  404. };
  405. })
  406. // Enhance the HTML5 download attribute to
  407. // allow drag&drop of files to the desktop:
  408. .directive('download', function () {
  409. return function (scope, elm) {
  410. elm.on('dragstart', function (e) {
  411. try {
  412. e.originalEvent.dataTransfer.setData(
  413. 'DownloadURL',
  414. [
  415. 'application/octet-stream',
  416. elm.prop('download'),
  417. elm.prop('href')
  418. ].join(':')
  419. );
  420. } catch (ignore) {}
  421. });
  422. };
  423. });
  424. }));