Wednesday, 9 March 2016

Ajax Chatter File Attachment

Putting here so I don't forget how to do it:

public string imageData {get;set;}
public string imageName {get;set;}
public string imageDescription {get;set;}
public string recordId {get;set;}
/*
 * imageData:        base64 encoded file starting with something like this - data:image/png;base64,iVBORw0KGgoAAAA...
 * imageName:        name of the file being uploaded
 * imageDescription: description of the file being uploaded
 * recordId:         ID of the record the uplaod is assocaited with
 */
public void submitImage(){
    String base64 = imageData.substring(imageData.indexOf(',')+1);
    Blob actualdata = EncodingUtil.base64Decode(base64);        
    /* Regular attachment */ 
    //Attachment a = new Attachment(
    //    parentId = recordId,
    //    name = imageName,
    //    body = actualdata,
    //    description = imageDescription
    //);
    //insert a;
    /* Chatter attachment */ 
    ContentVersion doc = new ContentVersion();
    doc.Title = imageName;
    doc.Description = imageDescription;
    doc.PathOnClient = imageName;
    doc.VersionData = actualdata;
    insert doc;
    FeedItem post = new FeedItem();
    post.Visibility = 'AllUsers';
    post.ParentId = recordId;
    post.CreatedById = UserInfo.getUserId();
    post.RelatedRecordId = doc.Id;
    post.Type = 'ContentPost';
    post.Title = 'File upload for ' + imageDescription;
    insert post;
    imageData = ''; // so it doesn't blow my page up!
}

No comments:

Post a Comment