[SalesForce] Upload Attachments to Files Related list using Apex

When user attaches files on Notes and Attachments related list from Salesforce UI then files gets attached to Files and Notes and Attachments related list.
But when I do it from vf page/apex then it just attaches it to Notes and Attachment related list.

Attachment myAttachment  = new Attachment();
myAttachment.Body = fileBody;
myAttachment.Name = fileName;
myAttachment.ParentId = aLead.id;
insert myAttachment;

Files uploaded to the Attachments related list on records are uploaded
as Salesforce Files, not as attachment

enter image description here

Best Answer

Like the option says it attaches files only when its uploaded from related list(Only from the standard related list UI). From apex you're supposed to insert a contentDocument, which is a salesforce file but what you're attaching is just an attachment. Salesforce doesn't automatically convert attachment into a file. You need to insert a file explicitly!

ContentDocument : Represents a document that has been uploaded to a library in Salesforce CRM Content or Salesforce Files. This object is available in versions 17.0 and later for Salesforce CRM Content. This object is available in API version 21.0 and later for Salesforce Files.

For more info please refer Difference between Attachments and ContentDocument along with How can I create a Chatter File via Apex?

Related Topic