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.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
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.
Note: If you want to learn more about why ng-change directive does not work with HTML FileUpload element (Input Type File), please refer Using ng-change with FileUpload (Input Type File) in 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 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.
Note: If you want to learn more about using ng-show directive with condition, please refer my article AngularJS: Show using ng-show if Variable (Model) 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
Preview Image before upload using AngularJS
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads