Sunday 9 July 2023

To display the photo of the current user in an SPFx web part using the Microsoft Graph API

 you can follow these steps:

  1. Install necessary dependencies:

    • Install the @microsoft/sp-http package by running the following command in your project's root directory:
      bash
      npm install @microsoft/sp-http
  2. Import the required modules and interfaces in your web part's TypeScript file:

    typescript
    import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http'; import { MSGraphClient } from '@microsoft/sp-http';
  3. Retrieve the photo URL from Microsoft Graph and display it in your web part:

    typescript
    // Get the photo URL using Microsoft Graph this.context.msGraphClientFactory .getClient() .then((client: MSGraphClient): void => { client .api('/me/photo/$value') .responseType('blob') .get((error, photoResponse: any, rawResponse?: any) => { if (photoResponse) { // Convert the photo response to a blob URL const blobUrl = URL.createObjectURL(photoResponse); // Display the photo in your web part const photoElement = document.createElement('img'); photoElement.src = blobUrl; this.domElement.appendChild(photoElement); } else { // Handle error console.error(error); } }); });

Remember to replace this.context with your web part's context object, which provides access to the SharePoint HTTP client and the Microsoft Graph client.

Make sure you have the necessary permissions and consent to access the user's photo.

No comments:

Post a Comment