<!DOCTYPE html>
<html>
<head>
<title>Upload File in AngularJs</title>
<link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<script>
console.clear();
angular.module('fileUpload', [])
.controller("upload", ['$scope', '$http', 'uploadService', function($scope, $http, uploadService) {
$scope.$watch('file', function(newfile, oldfile) {
if (angular.equals(newfile, oldfile)) {
return;
}
uploadService.upload(newfile).then(function(res) {
// DO SOMETHING WITH THE RESULT!
console.log("result", res);
})
});
} ])
.service("uploadService", function($http, $q) {
return ({
upload: upload
});
function upload(file) {
var upl = $http({
method: 'POST',
url: '', // /api/upload
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
upload: file
},
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function(value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
});
return upl.then(handleSuccess, handleError);
} // End upload function
// ---
// PRIVATE METHODS.
// ---
function handleError(response, data) {
if (!angular.isObject(response.data) || !response.data.message) {
return ($q.reject("An unknown error occurred."));
}
return ($q.reject(response.data.message));
}
function handleSuccess(response) {
return (response);
}
})
.directive("fileinput", [function() {
return {
scope: {
fileinput: "=",
filepreview: "="
},
link: function(scope, element, attributes) {
element.bind("change", function(changeEvent) {
scope.fileinput = changeEvent.target.files[0];
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope.filepreview = loadEvent.target.result;
});
}
reader.readAsDataURL(scope.fileinput);
});
}
}
} ]);
</script>
</head>
<div ng-app="fileUpload" class="container">
<div class="row" ng-controller="upload">
<div class="col-md-6">
<input type="file" fileinput="file" filepreview="filepreview" />
</div>
<div class="col-md-6">
<img ng-src="{{filepreview}}" class="img-responsive" ng-show="filepreview" />
</div>
</div>
</div>
</html>