angular http: how to call images with custom headers?

强颜欢笑 提交于 2019-11-28 07:35:58
Anthony O.

As said here you can use angular-img-http-src (bower install --save angular-img-http-src if you use Bower).

If you look at the code, it uses URL.createObjectURL and URL.revokeObjectURL which are still draft on 19 April 2016. So look if your browser supports it.

In order to use it, declare 'angular.img' as a dependency to your app module (angular.module('myapp', [..., 'angular.img'])), and then in your HTML you can use http-src attribute for <img> tag.

In your example it would be: <img http-src="{{element.image.url}}">

Of course, this implies that you have declared an interceptor using $httpProvider.interceptors.push to add your custom header or that you've set statically your header for every requests using $http.defaults.headers.common.MyHeader = 'some value';

There is a vary simple answer for that. You should use: angular-img-http-src.

Problem:

You used token based auth and you need to serve images from secured routes.

Solution:

Use http-src instead of ng-src and it will fetch images using the $http service - meaning Authorization headers added via interceptors will be present - then build a Blob and set the src to an objectURL.

It works perfectly on my project.

I am facing the same problem. The best solution I found is passing the Authorization token as a query parameter.

For example :

<img src="http://myhost.com/image/path?accessToken=123456789" >

This way you can secure those images only for your REST consumers.

Consider the URL be http://foo.com/bar.png

In your controller,

angular.module('foo')
  .controller('fooCtrl', ['$sce',
    function($sce) {
      $scope.dataSrc = "http://foo.com/bar.png"
      $scope.src = $sce.trustAsResourceUrl($scope.dataSrc)
    }
  ])

And in your view,

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

.. seems to do the trick.

As far as I know it's not possible to pass additional headers with asset requests (scripts, images, media, CSS files that the browser loads while rendering the page). That's all controlled by the browser. Only when making a XHR (AJAX) request can you modify headers.

I would suggest looking at your server side authentication and seeing if there's a solution there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!