Have you come across a use case where you wanted to display/share some images(or other file types), stored as Salesforce Files, outside of Salesforce?
Salesforce lets you handle this very effectively using the Content Delivery object; API Name: ContentDistribution.
To expose a file publicly, you can simply create a record on ContentDistribution object with a link to the respective ContentVersion Id.
Once you create a record of ContentDistribution type, there are 2 fields that get auto populated namely; DistributionPublicUrl and ContentDownloadUrl.
Both these fields contains a URL to expose the file as a public resource. If you’re wondering what’s the difference…
DistributionPublicUrl contains the URL of the shared file that can be previewed within a container. And it looks something like this:
This URL let’s you preview and download the file. However, if you wish to use it in a img tag to preview an image type file, it won’t work.
So how do we make it work?
Meet ContentDownloadUrl field.
ContentDownloadUrl contains the URL of the shared file that lets you directly download the file. And you can use this URL in img tag as source(src) to display the file.
What’s even more cool is ContentDistribution object tracks a bunch of other useful things as well, for example, ViewCount, FirstViewDate, LastViewDate. You can even make the shared file password protected!
You’d also create multiple ContentDistribution records for same file if you want track some stats based on different places where it’s being exposed.
And there is bunch of other stuff you can do with this object, check here.
How to create the ContentDistribution object record?
You can use the ‘Public Link’ quick action on File page, Apex or Flow to do this.
Using Public Link Quick action:
When the link is generated, behind the scenes, a ContentDistribution object record is created.
NOTE: The link that gets generated is the DistributionPublicUrl. So you’d need to query the ContentDownloadUrl separately if you want to use it as ‘source’ URL.
/* Getting ContentVersion file using ContentDocument Id */ ContentVersion file = [SELECT Id, Title FROM ContentVersion WHERE ContentDocumentId = '<Content Document ID>'].Id; /* Creating ContentDistribution record */ insert new ContentDistribution( Name = file.Title, ContentVersionId = file.Id, PreferencesAllowViewInBrowser= true );
SIDE NOTE: You can also use ContentAsset(Asset files) to expose the file as public resource however, that is slightly more complicated than this approach! 🙂
Hope you find this useful. Catch you in the next one! ✌
Thank you for being an awesome reader! Subscribe to ForcePanda to receive all the latest updates straight to your inbox. 🙂