2

I have some images stored as blob in mysql database. I want to display it in html. I get the response from the server like this:

{"data":[{"ClassImage":{"type":"Buffer","data":[91,111,98,106,101,99,116,32,70,105,108,101,93]}}],"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://192.168.1.19:80/getImage","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}

I don't really know what I'm doing. AFter searching I found that I have to convert the blob response to base64 and then create a temporary url for the image and use it to set the src for the image.

When I set the responseType to blob, the data part of the response is empty({}). When I don't set any response type I get it as [91,111,98,106,101,99,116,32,70,105,108,101,93].

This is the code:

$scope.getImage = function(){
        $http({
            method:'GET',
            url: $scope.ipForHttp+"getImage"
            // responseType:'arrayBuffer'
        })
        .then(function(response){
            var u8 = new Uint8Array(response.data[0].ClassImage.data);
            var b64encoded = btoa(String.fromCharCode.apply(null, u8));
            var file = new Blob(u8, {type: 'image/png'});
             $scope.fileURL = URL.createObjectURL(file);
             $scope.content = $sce.trustAsResourceUrl($scope.fileURL);

            console.log($scope.fileURL);
            console.log(JSON.stringify(response));
        })
    }

The html:

        <div>
            Image:
            <!-- <img ng-src="{{content}}"> -->
            <!-- <img data-ng-src="data:image/png;base64,{{b64encoded}}"> -->
            <img ng-src="{{fileURL}}">
            <p>{{fileURL}}</p>
        </div>

The fileURL I get after the createObjectURL isblob:http://192.168.1.19/6d5ab92f-7e86-4537-893c-f22826ed1b5a

When I do this I don't get the image. When I go to the url the page is blank. What am I doing wrong?

Abhi
  • 1,512
  • 2
  • 22
  • 46
  • 1
    saving images as blobs in a database is a bad idea. Saving images as base64 encoded data is a horrible one http://stackoverflow.com/a/38829952/267540 – e4c5 Sep 23 '16 at 10:05
  • @e4c5. yeah. this is user data..and my boss wants it to be as blob in database. can you please help me display it? – Abhi Sep 23 '16 at 10:13
  • 1
    sorry no, I refuse to contribute to bad practices. – e4c5 Sep 23 '16 at 10:15
  • @e4c5. can you at least tell me if i'm in the right track? – Abhi Sep 23 '16 at 11:01

1 Answers1

0

I just had to convert the response to base64 and display it.

$scope.getImage = function(){
    $http({
      method:'GET',
      url: $scope.ipForHttp+"getImage"
            // responseType:'arrayBuffer'
        })
   .then(function(response){

      $scope.b64encoded = btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));

        })
    }

And in html:

<img data-ng-src="data:image/png;base64,{{b64encoded}}">
Abhi
  • 1,512
  • 2
  • 22
  • 46