Search code examples
salesforcesalesforce-lightningsalesforce-communitieslwc

How to download all attachments of all records of a custom object in Salesforce?


I am new to file handling in Salesforce. I want to grab all the files attached to all the records of a custom object. Can anyone help me with it?


Solution

  • Old-school SF used Attachment object and you could simply go SELECT Body, ContentType, Name FROM Attachment WHERE ParentId = '...'.

    In Lightning there's high chance your attachments are called "Files" (the actual API name is ContentDocument / ContentVersion). Check if the attachment's ID starts with 068 or 069. They aren't linked directly to your record. Instead there's ContentDocumentLink table sitting in between, used to cross-share same file. (You upload it and waste database space once, then you can cross-link it in Chatter posts, groups, other records...)

    The official ERD isn't great, try to click through it in Setup -> Schema Builder or this answer might help: https://salesforce.stackexchange.com/a/160285/799. There's a sample query which you might have to fine-tune a bit, for example to SELECT ContentDocument.LatestPublishedVersion.VersionData to get the actual payload.

    Check out other questions around here about ContentVersion. For example https://stackoverflow.com/a/48668673/313628 (it's other way around, about upload but should give you good idea).