2014-09-02 46 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