In this article I will explain with an example, how to preview Image before upload using AngularJS.
When an Image File is selected in the HTML FileUpload element (Input Type File), the Image File data will be read using HTML5 FileReader API and displayed in Image element using AngularJS.
Preview Image before upload using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML markup consists of an HTML FileUpload element (Input Type File) and an Image element.
The HTML FileUpload element (Input Type File) has been assigned an OnChange event handler which calls the method inside Controller.
When an Image File is selected in the HTML FileUpload element (Input Type File), the Image File data will be read using HTML5 FileReader API and the Image data is assigned to a Model variable.
The Model variable is assigned to the ng-src directive which displays the Image in the HTML Image element.
The Image element is also assigned ng-show directive which shows the HTML Image element only when the Model variable is not NULL.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.SelectFile = function (e) {
var reader = new FileReader();
reader.onload = function (e) {
$scope.PreviewImage = e.target.result;
$scope.$apply();
};
reader.readAsDataURL(e.target.files[0]);
};
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="file" onchange="angular.element(this).scope().SelectFile(event)" />
<hr />
<img ng-src="{{PreviewImage}}" ng-show="PreviewImage != null" alt="" style="height:200px;width:200px" />
</div>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads