Blame view
resources/js/common/directives/imageUploader.js
3.62 KB
e77200db5 Initial commit |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
angular.module('footyroom') /** * Allows to upload images from users computer. Also allows to select image by * URL from the web. */ .directive('imageUploader', ['$http', 'upload', function ($http, upload) { return { templateUrl: '/views/ng/modal/insert-image.html?2', link: function (scope, element) { /** * Open system's file chooser. */ scope.fileChooser = function () { setTimeout(function () { element.find('input[type="file"]').trigger('click'); }, 0); }; /** * Add image that has been selected by user. */ scope.addImage = function () { if (scope.image) { element.litelay({ spinner: true }); uploadImage() .then(function (response) { scope.$close(response); }) .catch(function (errors) { scope.errors = errors; }) .finally(function () { element.litelay(); }); } else if (scope.imageUrl) { scope.$close(scope.imageUrl); } }; /** * Reset all user selections. */ scope.reset = function () { scope.image = null; scope.imageDataUrl = null; scope.imageUrl = null; scope.errors = null; }; /** * Upload image selected by user. */ function uploadImage() { return upload('/comments/upload-image', { max_file_size: 512000, image: scope.image, }) .then(function (response) { return response.data.url; }) .catch(function (response) { if (response.data.errors) { throw response.data.errors; } else if (response.status === 413) { // 413 error occurs when the request body is larger than the server is configured to allow. throw 'Image size exceeds maximum allowable size.'; } else { throw 'Something went wrong. Please try again.'; } }); } }, }; }]) .service('upload', ['$http', function ($http) { return function (url, data) { var formData = new FormData(); _.each(data, function (value, key) { formData.append(key, value); }); return $http.post(url, formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined}, }); }; }]) .directive('fileReader', [function () { return { scope: { file: '=', fileDataUrl: '=', }, link: function (scope, element) { element.bind('change', function (event) { scope.file = event.target.files[0]; var reader = new FileReader(); reader.onload = function (event) { scope.$apply(function () { scope.fileDataUrl = event.target.result; }); }; reader.readAsDataURL(scope.file); // Reset value of input element so that if we choose the same // file again the change event is still fired. this.value = null; }); }, }; }]); |