1

I've written an api service which fetch a binary data from $http. The problem is I don't know how to used that data to display the image. PS: the binary data is actually an image.

This is my service api

getAvatar: function() {
    return $http({
      method  : 'GET',
      url     : 'domain.com',
      headers : {'Content-Type' : 'application/json'}
    });
  }

My controller

//get avatar
$scope.userAvatar = function() {
    Api.getAvatar()
    .then(function(result) {
        //success
        console.log(result.data); //this is the binary data
        $scope.avatarImage = result.data;
        }

    }, function(result) {
        //errors
    });

};

At first I thought that result that the api will give me is a url but it turns out a binary. Do I have to convert it first?

1
  • If your API is built to return binary data, then surely if it is an image and encoded properly, why use ajax? why not simply set this as the src of an IMG element? Commented Aug 27, 2013 at 8:39

3 Answers 3

4

I assume your service may be returning the base64 encoded string of data for any image which you then bind it to avatarImage in your controller.

Then simply write in html:

<img ng-src="{{avatarImage}}"/>

Sign up to request clarification or add additional context in comments.

2 Comments

it turns out its pretty straight forward. Haha. thanks for all the help :)
Wow you made my day!
2

you can do this by creating a new image element

$img=$("<img src='data:image/gif;base64,"+result.data+"'/>"); //Assuming that the image was encoded as base64. Try this

$elem.append($img) whereever you want to insert it

Comments

0

Chek out ngSrc

Here is a example:

 <div ng-controller="Cont">
      <img ng-src="{{imageSource}}">
 </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.