3

I am using react-native-facebook-login in order to get user data. Its returning me the url of the profile picture. when I paste this url in the browser the picture gets downloaded. Its returning the following string named profile

{"id":"10210xxx114564932","name":"Stan Shivam","email":"[email protected]","first_name":"Shivam","last_name":"Stan","age_range":{"min":21},"link":"https:\/\/www.facebook.com\/app_scoped_user_id\/10210663114564932\/","picture":{"data":{"height":50,"is_silhouette":false,"url":"https:\/\/lookaside.facebook.com\/platform\/profilepic\/?asid=10210663114564932&height=50&width=50&ext=1523007905&hash=AeQ-_PZnt1JTbnth","width":50}},"gender":"male","locale":"en_GB","timezone":5.5,"updated_time":"2018-03-27T18:37:33+0000","verified":true}

What I want to do is I want to convert the url to base64 and send it to server. But I am not being able to find some good tut on this.

What I tried so far.

getBase64ImageFromUrl = async (imageUrl) => {
    const res = await fetch(imageUrl);
    console.log(res);
    const blob = await res.blob();

    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => {
          resolve(reader.result);
      }, false);

      reader.onerror = () => {
        return reject(this);
      };
      reader.readAsDataURL(blob);
    });
  }; 

calling it from constructor

this.getBase64ImageFromUrl('https://lookaside.facebook.com/platform/profilepic/?asid=10210663114564932&height=50&width=50&ext=1523007763&hash=AeSavHT5oXVEMq4w')
            .then(result => console.log(result))
            .catch(err => console.error(err));

But it gives me res.blob() is not a function. What exactly do I need to use in order to achive it.

1 Answer 1

3

I resolved this using FileReader. use the following function and pass the url and callback. Thanks

export const toDataUrl = (url, callback) => {
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
      const reader = new FileReader();
      reader.onloadend = () => {
          callback(reader.result);
      };
      reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
};

calling the function

toDataUrl('https://lookaside.facebook.com/platform/profilepic/?asid=10210663114564932&height=50&width=50&ext=1523007763&hash=AeSavHT5oXVEMq4w', (myBase64) => {
              console.log(myBase64); // myBase64 is the base64 string
            });
Sign up to request clarification or add additional context in comments.

1 Comment

if the url is stored on a remote server, like cloud storage, the above solution will not work as it will face the CORS issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.