How to create Files using Salesforce Apex and store it in a specific Library Folder?

How to create Files using Salesforce Apex and store it in a specific Library Folder?

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

To store the File inside a specific folder inside the library, create ContentDocumentLink record with the Content Version’s Content Document Id and Content Workspace Id(Library Id). Then, update the ContentFolderMember’s ParentContentFolderId with the Folder Id(ContentFolder record Id).

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
];
ContentWorkspace objCW = [ 
    SELECT Id
    FROM ContentWorkspace
    WHERE Name = 'Test'
    LIMIT 1
];
ContentDocumentLink objCDL = new ContentDocumentLink(
    ContentDocumentId = objCV.ContentDocumentId,
    LinkedEntityId = objCW.Id
);
insert objCDL;
ContentFolder objCF = [ 
    SELECT Id
    FROM ContentFolder
    WHERE Name = 'Test'
    LIMIT 1
];
ContentFolderMember objCFM = [
	SELECT Id, ChildRecordId, ParentContentFolderId
	FROM ContentFolderMember
	WHERE ChildRecordId =: objCV.ContentDocumentId
	ORDER BY CreatedDate DESC
	LIMIT 1
];
objCFM.ParentContentFolderId = objCF.Id;
update objCFM;

Leave a Reply