jquery.fileupload-angular.js 16 KB

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