1

We are calling an external API, this API returns back a Byte array which we will then try to display an image.

Our API is as follows:

$scope.GetImage = function () {

    $.ajax({
        type: 'GET',
        url: "https://MyURL/Service.svc/Media(guid'da1b080f-2558-4d06-b9ce-2fe5955c3a20')/$value",
        data: rBody,
        contentType: "image/png",
        success: function (data) {
            $("#photo").prepend('<img id="theImg" src="data:image/png;base64,' + data + '" />')

            console.log(data);
        },
        error: function (request, error) {
            console.log('error:' + error);
        }
    });
};

When this returns I log Data which displays as follows:

enter image description here

Now I'm having an issue trying to set the image data:image/png;base64 within my Success function of my ajax call. The error I see within the console is

GET data:image/png;base64,%EF%BF%BDPNG%1A%EF%BF%BD%EF%BF%BD%EF%BF%BDIHDR%EF%BF%…%EF%BF%BD%0B&%EF%BF%BD%EF%BF%BD%0B&%01%EF%BF%BD%1C%C8%B0%EF%BF%BD%EF%BF%BD net::ERR_INVALID_URL

Code Ratchet
  • 5,758
  • 18
  • 77
  • 141

1 Answers1

-1
$scope.GetImage = function () {

    $.ajax({
        type: 'GET',
        url: "https://MyURL/Service.svc/Media(guid'da1b080f-2558-4d06-b9ce-2fe5955c3a20')/$value",
        data: rBody,
        contentType: "image/png",
        success: function (data) {
            var reader = new window.FileReader();
            reader.readAsDataURL(data); 
            reader.onloadend = function() {
                base64data = reader.result;  
                $("#photo").prepend('<img id="theImg" src="'+base64data+'" />');              
                console.log(base64data);
            }

            console.log(data);
        },
        error: function (request, error) {
            console.log('error:' + error);
        }
    });
};

See: Convert blob to base64

Community
  • 1
  • 1
seahorsepip
  • 4,519
  • 1
  • 19
  • 30
  • thanks for supplying a snippet along with a link let me test it and come back to you. – Code Ratchet Jan 12 '16 at 22:05
  • just tested this but I get the error message Argument 1 of FileReader.readAsDataURL is not an object. on the line reader.readAsDataURL(data); – Code Ratchet Jan 13 '16 at 00:19
  • Digging through using Chromes developer tool bar I notice this error: Uncaught TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'. – Code Ratchet Jan 13 '16 at 00:24
  • Then what are you receiving for data? Since it's either an encoded file(base64 etc)or file blob :S And et::ERR_INVALID_URL seems like the get request itself already failed. Can you make a jsfiddle? – seahorsepip Jan 13 '16 at 00:53
  • Don't work I have this message: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob – davdomin Dec 08 '16 at 22:47