When getting the URL from the current user's profile via REST, the image tag is not able to display when the src is updated:
<img id="escMyPic" src="" alt="" />
<script type="text/javascript">
$.ajax({
url: strURL + "/_api/sp.userprofiles.peoplemanager/getmyproperties",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: MyPictureSucceeded,
error: MyPictureFailed
});
function MyPictureSucceeded(data) {
if(data.d.PictureUrl != null) {
$('#escMyPic').attr('src', data.d.PictureUrl);
}
}
function MyPictureFailed() {
alert('Error: Unexpected error loading profile picture.');
}
</script>
The return url looks like this in SharePoint Online: https://tenant-my.sharepoint.com:443/User%20Photos/Profile%20Pictures/email_address_MThumb.jpg?t=63601764394
It redirects to: https://tenant-my.sharepoint.com/User%20Photos/Profile%20Pictures/email_address_MThumb.jpg?t=63601764394
Using browser dev tools, you see the mime type that comes back is not image/jpg but text/plain. I've removed the query string parameter, and even placed the hard coded URL in the image tag src, but it just doesn't display. Also the response body in the dev tools is blank. It appears to be redirecting and authenticating before showing.
When placing the hard coded URL in the browser address bar, the picture shows fine, and the dev tools response header shows the picture as the contents of the URL, and the MIME type is image/jpg.
How do you get the profile image to show from a REST call?
In addition to /_api/sp.userprofiles.peoplemanager/getmyproperties
endpoint which returns PersonalUrl
property, user profile picture could be requested via _layouts/15/userphoto.aspx?size=<size>&accountname=<accountname>
page, where
size
- could be set to S/M/L
which stands for Small/Medium/Large
image sizeaccountname
- user account nameExample
var url = getMyPictureUrl(_spPageContextInfo.webAbsoluteUrl,_spPageContextInfo.userLoginName,"M");
$('#escMyPic').attr('src', url);
where
function getMyPictureUrl(webUrl,accountName,size){
return webUrl + "/_layouts/15/userphoto.aspx?size=" + size + "&accountname=" + accountName;
}