ContentVersion
with a name, description and a small content. In this case I will create a TXT file to keep it simple.
ContentVersion cv = new ContentVersion();
cv.Description = 'test description';
cv.PathOnClient ='test_file.txt';
cv.Title = 'test file '+DateTime.now();
cv.versiondata=Blob.valueOf('test file body');
insert cv;
After creating the file we want to relate to one or many existing records such as an Account, Opportunity or even a custom object record.
To do that we have to insert a ContentDocumentLink
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: cv.Id].ContentDocumentId;
cdl.LinkedEntityId ='ANY ID'; // <----- put your record id here, example: an account tid
cdl.ShareType = 'V';
insert cdl;
Now go to the associated record and see the file attachment. You will have to add the Files related list to the layout in case you don't have it yet.
Photo by Christin Hume on Unsplash