Upload And Set Office 365 Profile Image Using Microsoft Graph API

Vinodh
 
SharePoint MVP
February 6, 2019
 
Rate this article
 
Views
6455

In this article, I have explained how to change your profile image in Office 365 and set it into Office 365 from SharePoint online using Microsoft Graph API.
In my previous article, I explained how to fetch access tokens to consume Graph API. In this article, we will discuss how to change Office 365 profile image from SharePoint using Microsoft Graph API.

My previous articles related to Microsoft Graph API from the below links.

Update User Profile Photo

Users are able to update the Office 365 from the following endpoints. You can use either PATCH or PUT operations for updating the profile picture.

Graph API endpoint: https://graph.microsoft.com
PUT https://graph.microsoft.com/me/photo/$value
PUT https://graph.microsoft.com/users/{user id | user Principalname}/photo/$value
PUT https://graph.microsoft.com/groups/{id of the office 365 group}/photo/$value
PUT https://graph.microsoft.com/contacts/{ id }/photo/$value
PUT https://graph.microsoft.com/users/{user id | userpricipalname}/contacts/{id}/photo/$value
PUT https://graph.microsoft.com/users/{user id | userpricipalname}/contactfolders/{contactFolderId/contacts/{id}/photo/$value
PATCH https://graph.microsoft.com/me/photo/$value
PATCH https://graph.microsoft.com/users/{user id | user Principalname}/photo/$value
PATCH https://graph.microsoft.com/groups/{id of the office 365 group}/photo/$value
PATCH https://graph.microsoft.com/contacts/{ id }/photo/$value
PATCH https://graph.microsoft.com/users/{user id | userpricipalname}/contacts/{id}/photo/$value
PATCH https://graph.microsoft.com/users/{user id | userpricipalname}/contactfolders/{contactFolderId/contacts/{id}/photo/$value

Permissions

Retrieve user photo user.readwrite, user.readwriteall

Retrieve the group photo group.readwrite

Retrieve the contact photo contact.readwrite

So now, I am going to create a function named “requestToken()” to fetch the access token passed into the AJAX request header to authorize the API request.

Code

 function requestToken() {  
   
        $.ajax({  
            "async": true,  
            "crossDomain": true,  
            "url": "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie    
            "method": "POST",  
            "headers": {  
                "content-type": "application/x-www-form-urlencoded"  
 	           },  
 	           "data": {  
 	               "grant_type": "client_credentials",  
 	               "client_id ": "8baf0301-27df-44b1-b4fe-7911b9a918de", //Provide your app id    
 	               "client_secret": "DxSF1K+JKl7LWJK8+3Ibg4il5JM4qUvdwOtShsYNvEA=", //Provide your secret    
 	               "scope ": "https://graph.microsoft.com/.default"  
 	           },  
 	           success: function(response) {  
 	               console.log(response);  
 	               token = response.access_token;  
 	                 
 	           }  
 	  
 	       })  
 	   }

In the console window, you are able to see the success response that looks like below.
graph api response

In the next step, we are going to create a function “uploadPhoto()” to upload a photo to Office 365.
HTML

 	<div class="upload-btn-wrapper">  
 	  <button class="btn" type="button" onclick=" UploadPhoto();">Upload a file</button>  
 	  <input type="file" name="myfile" id="testFile" />  
 	</div>

REQUEST

 function uploadPhoto(){  
     var file = document.getElementById('testFile').files[0];  //FETCH THE FILE FROM FILE UPLOAD CONTROL
    
             $.ajax({  
             method: 'PATCH',   
             url: "https://graph.microsoft.com/v1.0/users/vinodhvignesh@sharepointtechie.onmicrosoft.com/photo/$value",  
             data:  file,                       //pass DATA from the variable file
             processData: false,   
             headers: {  
 	                'Authorization': 'Bearer ' + token,          // THE ACCESS TOKEN HERE ALREADY RECEIVED WHEN REQUEST TOKEN FUNCION CALLS
 	                 'Content-Type': 'image/jpeg'                // SET THE CONTENT TYPES AS IMAGE/JPEG
 	            },  
 	        }).success(function (response) {  
 	            alert("Photo uploaded successfully");  
 	        //  retriveuserPhoto();  
 	              
 	        }).error(function (error) {});  
 	  
 	      }

Now, add a Content Editor Web Part and render the HTML.
content editor graph api
 

photo upload
 
After successfully picking the image file, click “Upload a file” button.
 
graph upload
Now, I am going to create a function “retriveuserPhoto()” to retrieve the uploaded photo from Office 365.

GET https://graph.microsoft.com/users/{userid | userprincipalname} /size/photo/$value

A successful request returns the binary data of the image.

HTML

  1. <img id=”office365″ src=”>

Code

 function retriveuserPhoto(){  
     
             $.ajax({  
             method: 'GET',  
              
             url: "https://graph.microsoft.com/v1.0/users/vinodhvignesh@sharepointtechie.onmicrosoft.com/48x48/photo/$value",  //url with size of the photo
               
             headers: {  
                 'Authorization': 'Bearer ' + token,   // pass the access token here
 	                    
 	            },   
 	        }).success(function (image) {  
 	            console.log(image);  
 	             var blob = new Blob(  
 	              
 	              [image],  
 	              
 	              {type : 'image/jpeg'}  Convert the response into blob with content type image/jpeg                      
 	);   
 	var url = window.URL || window.webkitURL;  
 	var blobUrl = url.createObjectURL(blob);  // Use the javascript object to construct a blob image url
 	$('#office365').attr("src", blobUrl);  //bind the BLOB url into image tag
 	  
 	        }).error(function (error) {});  
 	  
 	      }

 

Output
Profile Image 1

Profile Image 2
Now, you are able to update and get photos from Office 365 using Microsoft Graph API.

Happy SharePointing!

Category : Graph API, Office 365

Author Info

Vinodh
 
SharePoint MVP
 
Rate this article
 
Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies. His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows ...read more
 

Leave a comment