3

After reseaches and tests, I still can't show an image form ReST API on my Angular App. I have images available on my ReST web service, why do I use a ReST service? Because in order to access you need to be authenticated (I use oAuth 2 protocol). When I use POSTMan (ReST client very usefull) everything works great, the image is displayed without doing nothing. But when I try to display it with Angular after a $http it doesn't work.

Here are the headers received form the service :

Content-Length → 51756
Content-Type → image/jpeg; charset=binary
Server → Apache/2.4.9 (Win64) PHP/5.5.12
X-Powered-By → PHP/5.5.12

Here is my Angular code :

var data64 = $base64.encode(unescape(encodeURIComponent(data)));
scope.src = 'data:image/jpeg;charset=binary;base64,' + data64;

and my HTML :

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

For information I use angular-base64 (https://github.com/ninjatronic/angular-base64) for the encodage. Without "unescape" and "encodeURIComponent" I have an error, I've tried to remove white spaces but it still doesn't work.

Thank you :)

LucasNesk
  • 183
  • 8
Nico
  • 35
  • 1
  • 6
  • why don't you directly put the REST-URL into ng-src? – wero Jul 21 '15 at 11:54
  • hello, because I need to add header, like I said I use an OAuth protocol, so I need to add some headers and a token... – Nico Jul 21 '15 at 11:57
  • got it. Your header says it is a `image/jpeg` but your data string starts with `ìmage/png`. And why do you include the `charset=binary`? – wero Jul 21 '15 at 12:13
  • Sorry I've forgot to change png to jpeg before copying, but it still doesn't work even if I remove the charset=binary... – Nico Jul 21 '15 at 12:25

2 Answers2

2

Seems that this will not work since you tell the browser that the image data is base64 encoded, but you also transformed it with unescape and encodeURIComponent.

Why don't you fetch your image data into a binary data structure (requires a modern browser), instead of into a string:

$http.get(req, {responseType: "arraybuffer"}).
    success(function(data) {
        $scope.src = 'data:image/jpeg;base64,' + _arrayBufferToBase64(data);
    });

_arrayBufferToBase64 is defined here.


A different approach would be to install a request interceptor, recognize the image url and add the oauth headers for this case.

wero
  • 32,544
  • 3
  • 59
  • 84
  • Nice ! :) It work for me. I'll test browsers for compatibility (It works on Chrome) Thank you – Nico Jul 21 '15 at 12:47
0

I tryed this way in angular 8+ and works fine:

imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
  this.imageToShow = reader.result;
}, false);
if (image) {
  reader.readAsDataURL(image);
}
}

and also call it like this:

getImageFromService() {
  this.api.getImage(key).subscribe(data => {
    this.createImageFromBlob(data);    
  }, error => {
    console.log(error);
  });
 }
B.Habibzadeh
  • 490
  • 6
  • 10