如何使用angularjs使用图像形式json响应?

时间:2021-01-08 19:36:37

I have api which return image corresponsding to the userID.

我有api返回与userID相对应的图像。

API code whcih return image:

API代码返回图片:

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"

获取图像的路线是“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 :

HTML代码:

<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:

如果我给api路径服务器路径然后我得到图像,但如果我在angularsjs代码中使用该api路径,我没有得到图像,我得到这样的响应:

�ޑ�����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.

我不知道为什么会这样,请告诉我是否有人知道这件事。

2 个解决方案

#1


1  

and in your html

并在你的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...

并从控制器中删除该功能...

#2


1  

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

就像HarishR说的那样“函数getImage($ id)”应该返回路径而不是图像,在你的情况下它会返回类似的东西 - /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

如果您的代码将所有图像存储在上传文件夹中,并且名称为userId,则不需要进行api调用

#1


1  

and in your html

并在你的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...

并从控制器中删除该功能...

#2


1  

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

就像HarishR说的那样“函数getImage($ id)”应该返回路径而不是图像,在你的情况下它会返回类似的东西 - /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

如果您的代码将所有图像存储在上传文件夹中,并且名称为userId,则不需要进行api调用