Friday, 1 July 2016

AngularJS read file base64 string and display

Step 1: In angular controller add folowing $scope.loadFile method.

myApp.controller("itemCtrl", ["$scope", "$state", function ($scope, $state) {
$scope.loadFile = function (element) {
            var preview = document.getElementById('imgProfile');
            var file = element.files[0];
            var reader = new FileReader();
            $scope.profilePicMimeType = file.type;
            $scope.profilePicName = file.name;
            reader.addEventListener("load", function () {
                preview.src = reader.result;
                $scope.profilePicString = reader.result.split(',')[1];
            }, false);

            if (file) {
                reader.readAsDataURL(file);
            }
        };
}]);

Step 2: In html view follow the following html code.

      <div>
            <label class="col-sm-3 col-md-2 control-label text-right">Profile Pic</label>
            <div class="col-sm-5 col-md-4">
                <input type="file" name="inputProfilePic" id="inputProfilePic" onchange="angular.element(this).scope().loadFile(this)" ng-model="vm.profilePicString" />
                <img id="imgProfile" width="200"/></div>
        </div>

No comments:

Post a Comment