Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active May 26, 2020 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croxton/75f3b641667e8de87168eae8eaded4e8 to your computer and use it in GitHub Desktop.
Save croxton/75f3b641667e8de87168eae8eaded4e8 to your computer and use it in GitHub Desktop.
How to get the contents of a file attached to an Account with SOQL (Salesforce).

Files attached to Accounts in Salesforce are not publicly addressable. This gist explains how to use them in another context, so that they can be accessed by non-authenticated users. It assumes you are able to query Salesforce with the REST API connected via OAuth 2.0.

  1. Get an account record identified by {id} and return any attached files:
SELECT Id, Name, (ContentDocumentid FROM AttachedContentDocuments) FROM Account WHERE Id = {id}
  1. Use (one of) the returned ContentDocumentids to retrieve the a link to latest version of the file you're interested in. This will return an API URL that can be used to retrieve the file contents:
SELECT VersionData FROM ContentVersion WHERE ContentDocumentId = 'XXXXXXXXX' AND IsLatest = true
  1. Request the API URL, e.g. /services/data/v46.0/sobjects/ContentVersion/YYYYYYYYY/VersionData to return the binary data of the file. You can either stream directly to the browser with appropriate headers, or (much better) save as a file and serve that to your non-authenticated users.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment