5

I am querying salesforce for some attachment data and it returns the data in binary format.

enter image description here

I have tried to convert the same to base64, but I have been quite unsuccessful so far. I have tried the btoa() method but it returns the The string to be encoded contains characters outside of the Latin1 range. error.

I tried to use the fileReader method i.e., readAsDataURL(), it returns the base64 string but unfortunately that doesn't represent the image.

COuld you please help me out as to how to convert the binary form of the data to base64encoded string?

Edit Ultimately, I want to show the image on the webpage with the data I am getting which I am unable to do

Sam
  • 1,311
  • 2
  • 23
  • 47
  • What are you trying to do with the data? – Yosef Weiner May 19 '16 at 14:23
  • Are you sure it's not just an encoding in the console display itself? Also, what do you mean by "doesn't represent the image"? – Boaz May 19 '16 at 14:23
  • @SkinnyJ, I am trying to show the image on the webpage. Once I get the data in base64 , I can show that using the src attribute on the image – Sam May 19 '16 at 15:01
  • @RobBrander: If I were to upload an image to the webpage and then read the data using fileReader() object, the base64 generated is totally different from what I get if I do the same with the data that was retrieved from the wbservice – Sam May 19 '16 at 15:04

1 Answers1

4

If you are retrieving that image from server, you have the choice of convert to base64 from the server (and serve it ready to the client), or you need to pass the URL of the image from server, and then read it and convert to base64 from client javascript. But if you retrieve that binary from server to client, client will be unable to parse it since the data is corrupted due the wrong sending method.

Example converting a URL to base64 (with Canvas or FileReader):

function convertImgToDataURLviaCanvas(url){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL("image/png");
        canvas = null; 
    };
    img.src = url;
}

function convertFileToDataURLviaFileReader(url){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            console.log(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

Conversion Fiddle:

http://jsfiddle.net/handtrix/yvq5y/

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69