Last active
August 29, 2015 13:57
-
-
Save g-alonso/9898710 to your computer and use it in GitHub Desktop.
Angular File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Module | |
// ------ | |
var upload = angular.module('Upload', []); | |
// Directive | |
// --------- | |
upload.directive('fileChange', function () { | |
var linker = function ($scope, element, attributes) { | |
// onChange, push the files to $scope.files. | |
element.bind('change', function (event) { | |
var files = event.target.files; | |
$scope.$apply(function () { | |
for (var i = 0, length = files.length; i < length; i++) { | |
$scope.files.push(files[i]); | |
} | |
}); | |
}); | |
}; | |
return { | |
restrict: 'A', | |
link: linker | |
}; | |
}); | |
// Factory | |
// ------- | |
upload.factory('uploadService', ['$rootScope', function ($rootScope) { | |
return { | |
send: function (file) { | |
var data = new FormData(), | |
xhr = new XMLHttpRequest(); | |
// When the request starts. | |
xhr.onloadstart = function () { | |
$rootScope.$emit('upload:loadstart', file.name); | |
}; | |
// When the request has failed. | |
xhr.onerror = function (e) { | |
$rootScope.$emit('upload:error', {e: e, filename: file.name}); | |
}; | |
// When the request has finished successfully | |
xhr.onreadystatechange=function(){ | |
if (xhr.readyState==4 && xhr.status==200) { | |
$rootScope.$emit('upload:finish', xhr.responseText); | |
} | |
if(xhr.status == 401){ | |
$rootScope.$emit('upload:error', {e: 'session_expired', filename: file.name}); | |
} | |
} | |
// Send to server, where we can then access it with $_FILES['file]. | |
data.append('file', file, file.name); | |
xhr.open('POST', iway.base_url+"sms_bulk/Loader/load"); | |
xhr.send(data); | |
} | |
}; | |
}]); | |
// <input type="file" multiple ng-model="files" file-change> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment