Anita Mehta
Anita Mehta

Reputation: 577

How can I use image form json response using angularjs?

I have api which return image corresponsding to the userID.

API code whcih return image:

public function getImage($id) {
        if(File::exists('uploads/'.$id.'.jpg')) {
            $image = File::get('uploads/'.$id.'.jpg');
            return Response::make($image, 200, array('content-type' => 'image/jpg'));
        } else {
            return Response::json(array('error'=>true,'details'=>'No image.'));
        }

}

Route to get image is "api/image/id"

AngularJS Code:

QAApp.controller('imgCtrl', function ($scope, $http) {

      $scope.image = function (id) {
             $http({
                              method: 'GET', 
                              url: server + 'api/image/' + id,
                            }).success(function(data){
                              console.log(data);
                             $scope.imageUrl= data; // if you sure what data is you URL 
                       })
              }
          }); 

HTML Code :

<div class="artst-pic pull-left" ng-controller="imgCtrl">
       <img ng-src="{{imageUrl}}" ng-init="image(q.userID)" alt="" class="img-responsive" />
 </div>

If I give the api path with server path then I get the image but if I am using that api path in angularsjs code, I didnt get image, I an getting the response like that:

�ޑ�����b���[����T��Ԏ�����{����O���Q(�b'��ձ�3]Ӵ������ۯ��I��U+��=>���i�C�~o�����/2fh�*������]Y�]�ƅ���ԋ��ʋj�ў��

I dont know why this is happen, please tell me if anybody know about this.

Upvotes: 1

Views: 2868

Answers (2)

Jitender Sharma
Jitender Sharma

Reputation: 119

Like HarishR said "function getImage($id)" should return the path not the image, In your case it will return something like - /uploads/id.jpg

Though you do not need to make an api call if your code is storing all images in uploads folder with the name of a userId

Upvotes: 1

harishr
harishr

Reputation: 18065

and in your html

<div class="artst-pic pull-left" ng-controller="imgCtrl">
       <img ng-src="uploads/{{q.UserID}}.jpg" class="img-responsive" />
 </div>

and remove the function from controller...

Upvotes: 1

Related Questions