3
votes

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 );
});
2

2 Answers

8
votes

Edit: new Buffer is deprected. Please use Buffer.from(response.data, 'binary').toString('base64');

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');
0
votes

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