Home SALESFORCEAPEX How to Insert files using Salesforce Apex

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”

Example to Insert Salesforce Files using Apex Class:
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;
Here ShareType is either V, C and I
V = Viewer permission. The user can explicitly view but not edit the shared file.
C = Collaborator permission. The user can explicitly view and edit the shared file.
I = Inferred permission. The user’s permission is determined by the related record. For shares with a library, this is defined by the permissions the user has in that library. Inferred permission on shares with libraries and file owners is available in API versions 21.0 and later. Inferred permission on shares with standard objects is available in API versions 36.0 and later.

You may also like

Leave a Comment