Skip to content

Instantly share code, notes, and snippets.

@g-alonso
Last active August 29, 2015 13:57
Show Gist options
  • Save g-alonso/9898710 to your computer and use it in GitHub Desktop.
Save g-alonso/9898710 to your computer and use it in GitHub Desktop.
Angular File Upload
// 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