Posting a file with angular.js
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
<input type="text" ng-model="endpoint" placeholder="http://fhir3.healthintersections.com.au/open/Binary" /> <br/>
<input type="file" file-model="selectedFile" placeholder="Select file to upload" /> <br/>
<button ng-click="uploadFile()">Upload</button>
{{selectedFile.name}}
</div>
JavaScript
var myApp = angular.module('myApp',[]);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
scope: {
'fileModel': '='
},
link: function(scope, element, attrs) {
element.bind('change', function(){
scope.$apply(function(){
var file = element[0].files[0];
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
debugger;
if (!scope.fileModel) {
scope.fileModel = {};
}
scope.fileModel.data = btoa(binaryString);
scope.fileModel.name = file.name;
scope.fileModel.size = file.size;
scope.fileModel.type = file.type;
};
reader.readAsBinaryString(file);
});
});
}
};
}]);
function MyCtrl($scope, $http) {
$scope.endpoint = '';
$scope.selectedFile = {};
$scope.uploadFile = function() {
if (!$scope.endpoint) {
return alert('You have not specified an endpoint to post to');
}
if (!$scope.selectedFile || !$scope.selectedFile.name || !$scope.selectedFile.data) {
return alert('You have not selected a file yet');
}
var options = {
headers: {
'Content-Type': $scope.selectedFile.type;
}
};
$http.post($scope.endpoint, $scope.uploadFile.data, options)
.then(function(success) {
alert('Successfully posted');
}, function(error) {
alert('Error posting');
debugger;
});
};
}