Skip to content

Instantly share code, notes, and snippets.

@itswadesh
Created March 27, 2017 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itswadesh/afe1d5b7daf075449f6353b797d088ec to your computer and use it in GitHub Desktop.
Save itswadesh/afe1d5b7daf075449f6353b797d088ec to your computer and use it in GitHub Desktop.
<html ng-app="myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">Upload File</button>
</div>
</html>
<script src="angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/savedata";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment