0

How can we fetch a user profile photo through Graph API and display into Web part in SPFX?

Here is my function to call Graph API to fetch Specific user's Profile Photo filtering through their UserPrincipleName:

private image() {
    this.context.msGraphClientFactory
    .getClient()
    .then((graphclient:MSGraphClient): void=>{
    graphclient
    .api('/users/[email protected]/photo/$value')
    .get((error,positionResponse:Blob,rawResponse?:any)=>{
    console.log(positionResponse)
    let binaryData = [];
     binaryData.push(positionResponse);  
    const blobUrl = window.URL.createObjectURL(new Blob(binaryData, {type: "image/jpeg"}));
    document.getElementById('user-img').setAttribute("src", blobUrl );
    })
    })
}

Is their any way to display the API Response Image into a Web part?

In the API Call .api('/users/[email protected]/photo/$value') when removing "$value" at the endpoint:

Response at console

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('abhishek.negi%40credentinfotech.com')/photo/$entity",
    "@odata.mediaContentType": "image/jpeg",
    "@odata.mediaEtag": "\"5725BAEE\"",
    "id": "360X360",
    "height": 360,
    "width": 360
}

Without removing "$value" at the endpoint, I am getting null in the console.

1 Answer 1

2

Change code as below, should work -

 this.context.msGraphClientFactory
  .getClient()
  .then(async (graphclient: MSGraphClient) => {
    let photo = await graphclient
        .api('/users/'+ mail +'/photo/$value')
        .responseType("blob")
        .get()
        .then((blob: Blob) : Promise<any> => {
          return new Promise(resolve => {
            const url = URL.createObjectURL(blob)
            // loading an in memory 
            let img = new Image()
            img.onload = () => {
              URL.revokeObjectURL(url)
              resolve(img)
            }
            img.src = url
            img.setAttribute('width', '24px');
            img.setAttribute('height', '24px');
            // loading an embedded html img tag
            document.getElementById(targetId).replaceWith(img);
          })
        });
       

  })

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.