Angular File Upload

Angular File Upload

by megaadriano

HTML

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div class="container">
    <div ng-controller="MyCtrl" class="row">
        <button class="btn btn-primary pull-right" ng-hide="images.length == 0" ng-click="clearAll()">Clear All</button>
         <h3 ng-bind="name"></h3>

        <input type="file" ng-click="$event = $event" ng-model="display" multiple onchange="angular.element(this).scope().upload(event)" accept="image/png, image/jpeg, image/gif" />
          {{display}}
        <div class="row">
            <div class="col-md-12"> <span ng-repeat='img in images'> <a href="#" ng-click="setImage($index)">
                 <img ng-src="{{img}}" 
                    alt="Generic placeholder thumbnail" style="max-height:100px;" class="thumbnail"/>
              </a>

            </span>

            </div>
        </div>
        <img ng-src="{{display}}" ng-hide="!display" />
         <h4>You have upload {{images.length}} images this session.
            </h4>

    </div>
  
</div>

CSS

body {
    margin-top:8px;
}
.row>img {
    width:100%;
    background-size:cover;
}
.thumbnail {
    max-width:100px;
    display:inline;
}
a {
    text-decoration:none;
}
.

JavaScript

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
    $scope.name = "Select Files to Upload";
    $scope.images = [];
    $scope.display = $scope.images[$scope.images.length - 1];
    $scope.setImage = function (ix) {
        $scope.display = $scope.images[ix];
    }
    $scope.clearAll = function () {
        $scope.display = '';
        $scope.images = [];
    }
    $scope.upload = function (obj) {
        var elem = obj.target || obj.srcElement;
        for (i = 0; i < elem.files.length; i++) {
            var file = elem.files[i];
            var reader = new FileReader();

            reader.onload = function (e) {
                $scope.images.push(e.target.result);
                $scope.display = e.target.result;
                $scope.$apply();
            }
            reader.readAsDataURL(file);
        }
    }

})