Files replaced Attachments in Salesforce. Now any type of document upload becomes part of Files/Content in Salesforce. With all the other advantages over Attachments, the best one is Files can be shared across objects, means having a attachment with multiple parents.
In lightning experience, any attachment upload is uploaded as files after Winter 16. But in salesforce classic you need to go to files settings and check “Files uploaded to the Attachments related list on records are uploaded as Salesforce Files, not as attachments” to make this happen. From then onwards Attachments will be uploaded as Files from classic too.
We all being uploading attachment in different ways one and of the ways is via Apex. Now how to upload Files as Attachment using Apex ? It is very simple you just need to understand the object relations and thats it.
This object record you don’t create. It gets created when you create Content Version who is child of ContentDocument. But Id of this record will be required to do other stuff.
This is where you attachment goes, you need to create this record in same way as you used to do for attachments
String yourFiles = 'Lets assume this is your binary string of the files'; ContentVersion conVer = new ContentVersion(); conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files conVer.PathOnClient = 'ionicLogo.png'; // The files name, extension is very important here which will help the file in preview. conVer.Title = 'Proposal '; // Display name of the files conVer.VersionData = EncodingUtil.base64Decode(yourFiles); // converting your binary string to Blog insert conVer;
This will insert your files but it will still not be visible under Attachment/Files related list. For that you need to create
This will share the files with users, records, groups etc. You can create multiple records to attach the same files under multiple records
// First get the content document Id from ContentVersion Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId; //Create ContentDocumentLink ContentDocumentLink cDe = new ContentDocumentLink(); cDe.ContentDocumentId = conDoc; cDe.LinkedEntityId = yourObjectRecord.Id; // you can use objectId,GroupId etc cDe.ShareType = 'I'; // Inferred permission, checkout description of ContentDocumentLink object for more details cDe.Visibility = 'InternalUsers'; insert cDe;
This will create files under your object records.