Rohit S
Rohit S

Reputation: 1

Image not displaying in html image tag

I am getting this response from the server for a jpeg image get request(with CORS): ÿØÿàJFIFÿÛ ( %!1"%)+.............

After converting this to base64 it using btoa(encodeURIComponent(data)) looks like: data:image/jpeg;base64,JUVGJUJGJUJEJUVGJUJGJUJEJUVGJUJGJUJEJUVGJUJGJUJEJTAwJTEwSkZJRiUwMCUwMSUwMSUwMSUwMEglMDBIJTAwJTAwJUVGJUJGJUJEJUVGJUJGJUJEJTAwJUVGJUJGJUJERXhpZiUwMCUwME1NJTAwKiUwMCUwMCUwMCUwOCUwMCUw...............................

On setting the img tag src attribute to the base64 above the image is not rendering in the browser.

However, when I open the image link in the browser tab, it loads properly. Also, on sending the same request in postman it renders the image in the response, in postman.

Even using the blob approach doesn't work (used bower: angular-img-http-src)

$scope.$watch('objectURL', function (objectURL) {
    elem.attr('src', objectURL);
});

$scope.$on('$destroy', function () {
    revokeObjectURL();
});

$http.get(url)
    .then(function (response) {
            var blob = new Blob(
                        [ response.data ], 
                        { type: response.headers('Content-Type') }
                    );

            $scope.objectURL = URL.createObjectURL(blob);

});

Kindly help here.

Upvotes: 0

Views: 1769

Answers (2)

Brian Peacock
Brian Peacock

Reputation: 1849

Though I don't know if there's a specific angular routine, the general JS solution for created images goes something like this...

function addIMG(durl, callback) {
    var img = new Image();
    img.addEventListener('load', function() {
        callback(this);
    }, false);
    img.src = durl;
}

addIMG(objectURL, function(img) {
    $('#element').appendChild(img);
});

Hope that helped :)

Upvotes: 0

Wasif Khan
Wasif Khan

Reputation: 954

In Service:

yourService : function(options) {

return $http.get(url, {
                    responseType : 'arraybuffer'
                }

        ).success(function(data) {
            var file = new Blob([ data ], {
                type : 'image/jpeg'
            });
            var fileURL = URL.createObjectURL(file);

            if(options && options.successCallBack) {
                return options.successCallBack(fileURL, {});
            }
        });
    },

In Controller:

function yourImageSuccessHandler(fileUrl, options) {
            $scope.objectUrl= fileUrl; // now you will have fileUrl in 
                                      // controller
        }
        yourService.getDownloadDoc(empId, {
            successCallBack: yourImageSuccessHandler
        });

In template HTML:

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

Upvotes: 0

Related Questions