1

Please let me elaborate the issue.

I am fetching user profile pic by hitting an api that is returning image as data as shown below in the screen shot

enter image description here enter image description here

I can not se the api url in the IMG tag src because I need to pass access token in the headers with the get request.

Here is the code that I am doing

vm.getDp = function () {
    if (vm.userDetails.hasDp) {
        userService.getProfilePic(vm.userDetails.id, vm.userDetails.profileImageUrl, accessToken)
            .then(function (data) {
                $("#theDp").attr('src', 'data:image/jpg;base64,' + data);
            }, function (error) {

            });
    }
}

enter image description here enter image description here

Vikas Bansal
  • 10,662
  • 14
  • 58
  • 100

1 Answers1

0

Since you are using AngularJS, lets stop using jQuery to do our stuff. You can use the ngSrc directive to bind scope variables to the src attribute of an image.

So by preparing your HTML with the directive

<img ng-src="{{vm.img_data}}" alt="Description" />

You can then show your image by setting the retrieved data.

vm.getDp = function () {
    if (vm.userDetails.hasDp) {
        userService.getProfilePic(vm.userDetails.id, vm.userDetails.profileImageUrl, accessToken)
            .then(function (data) {
                vm.img_data = 'data:image/jpg;base64,' + data;
            }, function (error) {

            });
    }
}

To prevent showing a broken image you could wrap your img element in a ngIf directive.

Example
Note the small red dot, which is the picture.

angular.module('app', []);

angular
  .module('app')
  .controller('ImageShower', ImageShower);

function ImageShower($scope) {
  var vm = this;
  vm.image_data = false;
  vm.title = 'Image Shower';

  activate();

  function activate() {
    vm.image_data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==';
  }
}
<!doctype html>
<html ng-app="app">

<head>
  <meta charset="utf-8">
  <title>Your Shopping Cart</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body ng-controller="ImageShower as vm">
  <h1>{{vm.title}}</h1>
  <img ng-src="{{vm.image_data}}" alt="Description" />
  <p>{{vm.image_data}}</p>
</body>

</html>
Maarten Bicknese
  • 1,498
  • 1
  • 14
  • 27