'How to get user's photo(profile) using Microsoft Graph API?

When a GET(https://graph.microsoft.com/v1.0/users/ {{user_id}} /photo/$value) request is made, the response data will be written with the same characters as image

image.

After converting to base64, I tried blob format but the picture does not appear.

router.js

router.get('/photo/:id',function (req,res) {
  auth.getAccessToken().then(function (token){
   let userId = req.params.id;
   graph.getUserPhotoData(token, userId).then(function (result) {
      res.json(result);
    }).catch(function (e) { console.log(e) })
  });
});

graph.js

function getUserPhoto(token, userId){
  return axios({
    method : 'get',
    url : 'https://graph.microsoft.com/v1.0/users/'+{{user_id}}+'/photo/$value',
    headers: {
      'Authorization':token,
      // 'Content-Type': 'image/jpeg',
    },
    responseType : 'blob'
  })
}


async function getUserPhotoData(token,userId) {
  try{
    let userPhoto = getUserPhoto(token,userId);
    let p = userPhoto.data;
    // let photo = new Buffer(userPhoto.data).toString('base64');
    return p; //...013O✿\u0011�e����|��>�4+�y��\u0017�"Y...
  }catch (e) { console.log(e);}
}

index.js

$.get('/photo/'+userId, function(response) {
  let binaryData = [];
  binaryData.push(response);  
  const blobUrl = window.URL.createObjectURL(new Blob(binaryData, {type: "image/jpeg"}));
  document.getElementById('user-img').setAttribute("src", blobUrl );
});


Solution 1:[1]

UPDATE: new Buffer is deprected. Please use

<img src={'data:image/jpeg;base64,' + Buffer.from(response.data, 'binary').toString('base64')}

Original answer

it works for me

const graphEndpoint = "https://graph.microsoft.com/v1.0/me/photo/$value";

const response = await axios(graphEndpoint, { headers: { Authorization: `Bearer ${token}` }, responseType: 'arraybuffer' });
const avatar = new Buffer(response.data, 'binary').toString('base64');

Solution 2:[2]

I solved this problem.

router.js

const request = require('request');

router.get('/photo/:id',function (req,res) {
  auth.getAccessToken().then(function (token){
    let userId = req.params.id;
    // graph.getUserPhotoData(token, userId).then(function (result) {
    //   console.log(result);
    //   res.json(result);
    // }).catch(function (e) { console.log(e) })
    request({ uri: 'https://graph.microsoft.com/beta/users/'+userId+'/photo/$value', method: "GET", headers:{'Authorization' : 'Bearer' + token}, encoding: null},
    function(error, response, body) {
      let data = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
      res.send(data); //data:image/jpeg;base64,/9j/4AAQSkZJRg...
    });
  });
});

index.js

$.get('/photo/'+ userId, function(response) {
  document.getElementById('user-img').setAttribute("src", response);
});

'graph.js' is not needed.

reference : Node.js get image from web and encode with base64

Solution 3:[3]

Finally found a solution to this! The previous answers didn't quite work for me. What I found that worked was:

const { data: photoValue} = await axios.request({
          method: 'GET',
          { headers: { Authorization: `Bearer ${token}` },
          responseType: 'blob',
          url: 'https://graph.microsoft.com/v1.0/me/photo/$value',
        });

const blobUrl = window.URL.createObjectURL(photoValue);

and then displaying it with <img src={blobUrl} />. This is the shortest answer in my opinion, and relies on the responseType: 'blob' being given.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vladimir Marton
Solution 2 sojung
Solution 3 Aron Atilla Hegedus