How to Insert files using Salesforce Apex
Salesforce Introduced the Salesforce Files feature as a part of Winter’16 and the salesforce file is going to replace Notes & Attachment.
Salesforce Files stored now instead of Attachment to Salesforce File Object called “ContentVersion“.
Salesforce Files in Lightning Experience:
Salesforce Files are available in Files home for users to share and manage. By contrast, an attachment to a record is available only from the record. Uploading a file as a Salesforce File instead of an attachment doesn’t change access to the file. It just makes the file available to share and manage beyond the specific record. This setting applies to Salesforce Classic only.
How To Enable to Salesforce Files:
From Setup -> Salesforce Files -> Enable “Files uploaded to the Attachments related list on records are uploaded as Salesforce Files, not as attachments”
String yourFilesContent = 'TheBlogReaders.com File upload content'; ContentVersion conVer = new ContentVersion(); conVer.ContentLocation = 'S'; // to use S specify this document is in Salesforce, to use E for external files conVer.PathOnClient = 'testing.txt'; // The files name, extension is very important here which will help the file in preview. conVer.Title = 'Testing Files'; // Display name of the files conVer.VersionData = EncodingUtil.base64Decode(yourFilesContent); // converting your binary string to Blog insert conVer; //Insert ContentVersion // First get the Content Document Id from ContentVersion Object Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId; //create ContentDocumentLink record ContentDocumentLink conDocLink = New ContentDocumentLink(); conDocLink.LinkedEntityId = '0066F00000qNVUv'; // Specify RECORD ID here i.e Any Object ID (Standard Object/Custom Object) conDocLink.ContentDocumentId = conDoc; //ContentDocumentId Id from ContentVersion conDocLink.shareType = 'V'; insert conDocLink;
- Overview of Salesforce Files
- Trailhead Module for Work with Notes and Files
- Example to Insert Content Note Using Salesforce Apex Class – https://theblogreaders.com/capture-parentid-contentnote-salesforce/
- Convert Attachments to Files using Magic Mover for Notes and Attachments to Lightning Experience on AppExchange
- Comparing Files and Attachments features
- Differences Between Files, Salesforce CRM Content, Salesforce Knowledge, Documents, and Attachments
- Migrate notes and attachments to Lightning