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; }); }, }; }]);