function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Aditi Singh 41Aditi Singh 41 

How to get ContentDocument file body in apex code?

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Aditi,

Can you please check the below Stack exchange question which is similar. You can use the similar SOQL to get it.

https://salesforce.stackexchange.com/questions/215115/how-to-retrieve-the-file-content-for-a-contentdocument-object

If this solution helps, Please mark it as best answer.

Thanks,
 
Aditi Singh 41Aditi Singh 41
I want to get file body.
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Aditi,

By using the below SOQL query you will get the  link some thing like below
 
/services/data/v53.0/sobjects/ContentVersion/0685j000000B6I0AAK/VersionData


Run a REST GET request hitting this url. It should give you the file content. You can try this via WORKBENCH, which downloads your file. If you try the same using REST API call in apex, it should give you the body of the file.

Give a try and see if it works.

Sample Http REST request is below. Replace the Id of the ContentVersion in below code and it returns you the file body.
 
Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v42.0/sobjects/ContentVersion/06890000003oTkqAAE/VersionData'); 
req.setMethod('GET'); req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId()); req.setHeader('Content-Type', 'application/json'); HttpResponse res = h.send(req); system.debug(res.getBody());

Thanks,
 
Aditi Singh 41Aditi Singh 41
Actually from this code I getBody in encrypted format and I need in base64 format.User-added image
Roman Stepanov 17Roman Stepanov 17

You dont need to perform REST, you can just get VersionData and make it String:

ContentVersion file = [SELECT Title, VersionData FROM ContentVersion WHERE IsLatest = TRUE LIMIT 1]
String body = file.VersionData.toString();
And in body you will see full body of the file

 

 

João AlmeidaJoão Almeida

Actually, to get the file content without using salesforce web service is the following (file blob must be base64 encoded):

ContentVersion file = [SELECT Title, VersionData FROM ContentVersion WHERE IsLatest = TRUE and ContentDocumentId=:contentDocId];
String bodyBase64 = EncodingUtil.base64Encode(file.VersionData);