2014-09-02 118 views
1

我有api返回的图像对应于userID。如何使用angularjs使用图像形式的json响应?

API代码whcih返回图像:

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.')); 
     } 

} 

路线到达图像“API /图像/ ID”

AngularJS代码:

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

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

如果我给与服务器路径API的路径,然后我得到的图像,但如果我使用angularsjs代码,API路径,我没有得到的图像,我的得到这样的回应:

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

我不知道为什么发生这种情况,请告诉我是否任何人都知道这一点。

+1

你正在找回是实际的图像,而不是它的URL。只需在'ng-src'中指定图像路径,而不是取回实际图像。 – harishr 2014-09-02 04:52:05

+0

当我使用“http://本地主机:8000/API /图片/ 7”直接在浏览器中,然后我得到的图像,以及相同的,如果在我的angularjs代码中使用它,它会返回响应,我有post.I不要知道如何获得图像的URL,请看我的代码,并告诉我哪里出错.... – 2014-09-02 05:00:11

+0

只需通过更改为下面的代码' harishr 2014-09-02 05:03:10

回答

1

的名称,并在HTML

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

并从控制器的功能...

+0

你试过了上面的代码吗?它工作吗? – harishr 2014-09-02 05:28:13

+0

是的,我知道了,但上传文件夹不在数据库中... – 2014-09-02 05:30:03

+0

,不需要在数据库中...文件可以从文件系统... – harishr 2014-09-02 05:30:49

1

HarishR“功能的getImage($ ID)”应该返回的路径而不是图像, 在你的情况下,它会返回类似 - /uploads/id.jpg

虽然你不需要调用API如果您的代码存储在文件夹上传的所有图片与用户ID