How to display image obtained as byte array in Angular JS

I have a server side application that will return an image. These are the response headers:

Content-Disposition: attachment; filename=8822a009-944e-43f4-999b-d297198d302a;1.0_low-res Content-Length: 502343 Content-Type: image/png Date: Mon, 03 Aug 2015 19:13:39 GMT Server: Apache-Coyote/1.1 

In angular, I need to display an image. When receiving the image, I use angularJS $http to call the server and put the result in scope, but I never achieve the success function of $http . Making this call from the postman usually returns an image. I am wondering how to get Angular to display an image.

This is how I display the image:

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

Here is the call to get the image from the server:

 $http.get(url, {responseType: "arraybuffer"}) .success(function(data) { $scope.image= data; } ) 
+6
source share
3 answers

I agree with Bell's answer that you should use the .then function and not the .success function on the promise returned from $http.get . However, I would suggest that you still have a problem with your ng-src link, since you are not supplying it with a URL, but instead referring to your byte array.

To bind your ng-src link to an array of bytes stored in memory on the client, your binding should have the following form:

 <img ng-src="data:image/JPEG;base64,{{image}}"> 

Edit

Since I never mentioned this explicitly, the ng-src binding above assumes your image data is in base64 format. HarrisonA provided the method below to convert the array if it is not already in base64 format.

+6
source

Just wanted to add jdmcnair and Loshmeey's comment to the answer:

Below is a link to a function that I used to convert an array buffer to a base 64 string.

ArrayBuffer for base64 encoded string

Function:

 function _arrayBufferToBase64( buffer ) { var binary = ''; var bytes = new Uint8Array( buffer ); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode( bytes[ i ] ); } return window.btoa( binary ); } 

I used this function in my angular controller and then passed the result (using the $ scope variable) to the img element in my html file.

+7
source
  • I think you should use a callback then , the angular documentation says that callback success is deprecated.
  • Your img is in the data properties.

After these considerations, you can try something like this.

 $http.get(url, {responseType: "arraybuffer"} ).then(function(response) { $scope.image= response.data; }); 
+2
source

All Articles