Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Visualforce component demonstrating the use of ConnectApi to upload Chatter profile photo
<apex:component selfClosing="true"
controller="CommunityUserPhotoUploadController"
allowDML="true">
<apex:attribute name="subject" type="Id"
assignTo="{!userId}"
required="true"
description="The User ID for the community user"/>
<apex:form>
<apex:image value="{!largePhotoUrl}"/>
<apex:inputFile value="{!blobValue}"
contentType="{!contentType}"
fileName="{!filename}"/>
<apex:commandButton value="Upload"
action="{!upload}"/>
</apex:form>
</apex:component>
/*
* Controller for the CommunityUserPhotoUpload component
*/
public class CommunityUserPhotoUploadController {
/*
* The binary data of the image uploaded by the user
*/
public transient Blob blobValue { get; set; }
/*
* The content type, determined by Salesforce, of
* the image uploaded by the user
*/
public transient String contentType { get; set; }
/*
* The name of the image file uploaded by the user
*/
public transient String filename { get; set; }
/*
* The User ID of the community user for which
* a new profile photo is being uploaded
*/
public Id userId { get; set; }
/*
* @return the URL for the large profile photo of the specified
* user in the current community
*/
public String getLargePhotoUrl() {
return ConnectApi.ChatterUsers.getPhoto(
Network.getNetworkId(), userId).largePhotoUrl;
}
/*
* @return the appropriate next page after setting the
* specified user's profile photo to the new
* image uploaded
*/
public PageReference upload() {
ConnectApi.BinaryInput photoFileInput =
new ConnectApi.BinaryInput(blobValue, contentType, filename);
ConnectApi.ChatterUsers.setPhoto(
Network.getNetworkId(), userId, photoFileInput);
return null; // Leave the user on the current page
}
}
<apex:page >
<!-- Demo page showing how to use the
CommunityUserPhotoUpload component -->
<c:CommunityUserPhotoUpload subject="{!$User.Id}"/>
</apex:page>
@TrevorYager
Copy link

TrevorYager commented Jul 22, 2015

Your code worked like a charm. The only problem i encountered is when i chose upload without selecting an image first. Your code will blow up due to no blobValue on line 44-45. All you need to do is wrap it in an if statement.

if (blobValue != null) {
ConnectApi.BinaryInput photoFileInput = new ConnectApi.BinaryInput(blobValue, contentType, filename);
ConnectApi.ChatterUsers.setPhoto(Network.getNetworkId(), UserInfo.getUserId(), photoFileInput);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment