Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
});
like image 303
sojung Avatar asked Dec 24 '22 07:12

sojung


1 Answers

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');
like image 147
Krystian Mateusiak Avatar answered Jan 15 '23 19:01

Krystian Mateusiak