How to create Files using Salesforce Apex?

How to create Files using Salesforce Apex?

We can make use ContentVersion entity to create files using Salesforce Apex. 

Use ContentDocumentLink entity to link the created the file to a record in Salesforce.

Sample Code:

String base64Content = EncodingUtil.Base64Encode( 
    Blob.valueOf( 'Testing File' ) 
);
System.debug( 'Base64 Content is ' + base64Content );
Blob blobContent = EncodingUtil.base64Decode( base64Content );
System.debug( 'Decoded Base64 value is ' + blobContent.toString() );
ContentVersion objCV = new ContentVersion(
    Title = 'Test',
    PathOnClient = 'test.txt',
    VersionData = blobContent 
);
insert objCV;
objCV = [
    SELECT ContentDocumentId
    FROM ContentVersion
    WHERE Id =: objCV.Id
];
ContentDocumentLink objCDL = new ContentDocumentLink(
    ContentDocumentId = objCV.ContentDocumentId,
    LinkedEntityId = '0013t00002XXRyDAAX',
    Visibility = 'AllUsers'
);
insert objCDL;

Output:

Leave a Reply