angular http: how to call images with custom headers?

François Romain picture François Romain · Feb 6, 2014 · Viewed 18.3k times · Source

In the html view, images are displayed like this:

<img ng-src="{{element.image.url}}"> 

element.image.url points to an url like: /rest_api/img/12345678.

This is working fine, images are displayed.

Now, I add authentication:

Before the user is authenticated, every resources respond with an http error 401, images too. When authentication succeeds, a token is placed in a custom headers and sent with every $http requests, allowing access the resources:

$http.defaults.headers.common['Authorization'] = token; 

This is working fine for Json files loaded with $resource. But the direct links to the images are still 401 after authentication.

How to call the images with custom headers?

Or any advice on how I should do this.

Answer

Anthony O. picture Anthony O. · Apr 28, 2016

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';