How can I create a Chatter File via Apex?

From the Chatter tab I can go to ‘Files’ and then upload a file without attaching it to anything.

I am wanting to know if there is a way to achieve the exact same thing via Apex?

Answer

If you’re asking how to upload files via Visualforce, or even just via Apex, there are code samples around: https://github.com/TehNrd/Multi-File-Uploader-Force.com shows how to upload via Visualforce to the Attachments object.
To upload a File in general, you want to go to the ContentVersion object.

This is some code I wrote a while ago:

public static ContentVersion generateContentVersionFile(Boolean doInsert) {
    return generateNewContentVersionVersion(null, doInsert);
}

public static ContentVersion generateNewContentVersionVersion(Id contentDocId, Boolean doInsert) {
    ContentVersion cont = new ContentVersion();

    if (contentDocId != null) {
        cont.ContentDocumentId = contentDocId;
    }

    cont.Title = 'Title for this contentVersion';
    cont.PathOnClient = 'file_' + Datetime.now().getTime() + '.txt';
    cont.VersionData = Blob.valueOf('My Content in file_' + Datetime.now().getTime() + '.txt');
    cont.Origin = 'H';

    if (doInsert) {
        insert cont;
    }

    return cont;
}

public static FeedItem generatePostWithRelatedDocument(Id parent, Id contentVersionId) {
    FeedItem elm = new FeedItem(Body = 'Post with related document body', ParentId = parent, RelatedRecordId = contentVersionId, Type = 'ContentPost');
    insert elm;
    return elm;
}

Attribution
Source : Link , Question Author : luke.mcfarlane , Answer Author : DavidSchach

Leave a Comment