Angularjs File Upload with image preview
View Live Example : http://jsfiddle.net/ICPradeep/y27e4knm/1/
JS
var myApp = angular.module(‘myApp’,[]);
myApp.directive(‘customOnChange’, function() {
return {
restrict: ‘A’,
link: function (scope, element, attrs) {
var onChangeFunc = scope.$eval(attrs.customOnChange);
element.bind(‘change’, onChangeFunc);
}
};
});
function MyCtrl($scope) {
$scope.data = ‘none’;
$scope.dataimg = ‘none’;
$scope.add = function(){
alert(‘d’);
var f = document.getElementById(‘file’).files[0],
r = new FileReader();
r.onloadend = function(e){
$scope.data = e.target.result;
var img = document.createElement(‘img’);
img.src = ‘data:image/jpeg;base64,’ + btoa(e.target.result);
document.body.appendChild(img);
}
r.readAsBinaryString(f);
}
}
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
HTML
<div ng-controller=”MyCtrl”>
<input type=”file” id=”file” name=”file” custom-on-change=”add”/>
<br>
<img scr={{dataimg}}/>
<p>{{data}}</p>
</div>