galleryUpload.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. angular.module("robware").controller('galleryUpload', ["$scope", "$http", function($scope, $http) {
  2. $scope.images = [];
  3. $scope.contextMenuActions = {
  4. Remove: remove,
  5. Clear: clear
  6. };
  7. function remove(containerScope) {
  8. if (!containerScope.image)
  9. return;
  10. var index = $scope.images.indexOf(containerScope.image);
  11. if (index !== -1)
  12. $scope.images.splice(index, 1);
  13. }
  14. function clear() {
  15. if (confirm("Are you sure you want to clear the uploads?"))
  16. $scope.images = [];
  17. }
  18. function removeImages(toRemove) {
  19. // I need this roundabout way to work with Angular's view engine
  20. var imageReferences = [];
  21. angular.forEach(toRemove, function(index) {
  22. imageReferences.push($scope.images[index]);
  23. });
  24. angular.forEach(imageReferences, function(ref) {
  25. $scope.images.splice($scope.images.indexOf(ref), 1);
  26. });
  27. }
  28. $scope.getTotalImageSize = function() {
  29. var totalSize = 0;
  30. angular.forEach($scope.images, function(image) {
  31. totalSize += image.file.size;
  32. });
  33. return totalSize;
  34. }
  35. $scope.safeUploadSize = function() {
  36. return $scope.maxUploadSize * 0.95;
  37. }
  38. $scope.fileDrop = function(files) {
  39. angular.forEach(files, function(file) {
  40. var imageObject = {
  41. file: file,
  42. title: file.name.replace(/\.[^/.]+$/, ""),
  43. description: "",
  44. preview: ""
  45. };
  46. var reader = new FileReader();
  47. reader.onload = function(e) {
  48. imageObject.preview = e.target.result;
  49. $scope.$apply();
  50. };
  51. reader.readAsDataURL(file);
  52. $scope.images.push(imageObject);
  53. });
  54. };
  55. $scope.upload = function() {
  56. var data = new FormData();
  57. var errors = [];
  58. angular.forEach($scope.images, function(image) {
  59. if (!image.title)
  60. errors.push("The image " + image.file.name + " doesn't have a title");
  61. data.append("files[]", image.file);
  62. data.append("title[]", image.title);
  63. data.append("description[]", image.description);
  64. });
  65. var totalSize = 0;
  66. data.getAll("files[]").forEach(function(entry){
  67. totalSize += entry.size;
  68. });
  69. if (totalSize>$scope.safeUploadSize())
  70. errors.push("Max upload size exceeded");
  71. if (errors.length>0){
  72. $scope.showErrors(errors);
  73. return;
  74. }
  75. $http({
  76. method: 'POST',
  77. url: '/gallery/uploadimages',
  78. data: data,
  79. showSpinner: true,
  80. headers: {'Content-Type': undefined},
  81. transformRequest: angular.identity
  82. }).then(function(response) {
  83. $scope.showErrors(response.data.errors);
  84. removeImages(response.data.uploaded);
  85. });
  86. };
  87. }]);