Introduction
Sometimes we need to show user profile image(to left menu or list of users profiles to grid) from SharePoint UserProfiles. While fetching user profile images, we faced an issue like site was asking for user credentials again even user logged into SharePoint site. In this article we will see the resolution for the issue.
Issue:
UserProfile user = UserProfileManager.GetUserProfile(Guid);
UserProfileValueCollection pictureURL = user[PropertyConstants.PictureUrl];
Image.Src = pictureURL.Value.ToString();
Output:
<img src="http://servername:8080/User%20Photos/Profile%20Pictures/user_image_name.jpg" />
Resolution:
We have resolved the issue by using _layouts/15/userphoto.aspx page to fetch user image instead of assigning direct picture URL from SharePoint user profile.
UserProfileValueCollection pictureURL = user[PropertyConstants.PictureUrl];
UserProfileValueCollection accountName = user[PropertyConstants.AccountName];
if (pictureURL != null && pictureURL.Value != null && accountName != null && accountName.Value != null)
{
string userImagePath = string.Format("{0}/_layouts/15/userphoto.aspx?accountname={1}&size=M&url={2}", SPContext.Current.Web.Url,accountName.Value.ToString(), pictureURL.Value.ToString());
Image.Src = userImagePath;
}
Output:
<img src="http://servername:8080/site1/_layouts/15/userphoto.aspx?accountname=domain\username&size=M&url=http://servername:8080/User%20Photos/Profile%20Pictures/user_image_name.jpg"/>
Code to fetch User Image from SharePoint Client Object Model:
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
userProfileProperties = peopleManager.getMyProperties();
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(Success, Fail);
function Success()
{
var picUrl = '/_layouts/15/userphoto.aspx?accountname=' + userProfileProperties.get_accountName() + '&size=M&url=' + userProfileProperties.get_pictureUrl();
$('#profile-image').attr('src', picUrl); //assign picture url to img src element
}
function Fail()
{
alert("Error occurred while fetching user profile");
}