AngularJS File Preview before Upload

Getting Started

I've used CDN for Bootstrap and Angular JS in this tutorial so you need internet connection for them to work.

Creating our HTML

This contains our input file and the place where we want our preview.
  1. <!DOCTYPE html>
  2. <html >
  3.         <title>AngularJS File Preview before Upload</title>
  4.         <meta charset="utf-8">
  5.         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  6.         <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  7. </head>
  8. <body ng-app="app" ng-controller="uploader">
  9. <div class="container">
  10.         <h1 class="page-header text-center">AngularJS File Preview before Upload</h1>
  11.         <div class="row">
  12.                 <div class="col-md-3">
  13.                         <h3 class="text-center">Upload File</h3>
  14.                         <hr>
  15.                         <label>File:</label>
  16.                         <input type="file" file-input="files">
  17.                 </div>
  18.                 <div class="col-md-9">
  19.                         <div ng-show="filepreview">
  20.                         <img ng-src="{{filepreview}}" height="300px" width="300px">
  21.                         <h4>Filename: {{ name }}</h4>
  22.                         <h4>Size: {{ size }}</h4>
  23.                         </div>
  24.                 </div>
  25.         </div>
  26. </div>
  27. <script src="angular.js"></script>
  28. </body>
  29. </html>

angular.js

This contains our angular.js code wherein we created a directive to handle out file input for our preview.
  1. var app = angular.module('app', []);
  2. app.directive('fileInput', ['$parse', function ($parse) {
  3.         return {
  4.       $scope: {
  5.         fileinput: "=",
  6.         filepreview: "="
  7.       },
  8.       link: function($scope, element, attributes) {
  9.         element.bind("change", function(changeEvent) {
  10.                 $scope.fileinput = changeEvent.target.files[0];
  11.                 var reader = new FileReader();
  12.                 reader.onload = function(loadEvent) {
  13.                 $scope.$apply(function() {
  14.                         $scope.filepreview = loadEvent.target.result;
  15.                 });
  16.                 }
  17.                 reader.readAsDataURL($scope.fileinput);
  18.                 $scope.name = $scope.fileinput.name;
  19.                 $scope.size = $scope.fileinput.size;
  20.         });
  21.       }
  22.     }
  23. }]);
  24. app.controller('uploader', function($scope, $http){
  25.  
  26. });
That ends this tutorial. Happy Coding :)

Add new comment