Creating A Public URL For Salesforce Files

Have you encountered a scenario in which you needed to showcase or distribute images (or other file formats) stored as Salesforce Files beyond the Salesforce platform?

To make a file accessible to the public, you can easily generate a record on the ContentDistribution object linked to the corresponding ContentVersion Id.

Upon creating a ContentDistribution record, two fields are automatically populated: DistributionPublicUrl and ContentDownloadUrl.

Both these fields provide URLs to make the file accessible as a public resource. If you’re curious about the distinction…

The DistributionPublicUrl comprises the URL of the shared file that can be previewed within a container. It typically appears as follows:

This URL allows you to preview and download the file. However, if you intend to utilize it within an img tag for previewing an image file, it won’t function as expected.

How can we make it function as intended? Enter the ContentDownloadUrl field.

The ContentDownloadUrl contains the URL of the shared file, enabling direct file downloads. This URL can be used within an img tag as the source (src) to display the file.

Exciting, isn’t it?

What’s even more fascinating is that the ContentDistribution object keeps track of various useful metrics, including ViewCount, FirstViewDate, and LastViewDate. You can even add a password protection layer to the shared file!

If you want to monitor statistics based on different locations where the file is exposed, you can create multiple ContentDistribution records for the same file.

And there’s a myriad of other functionalities you can explore with this object, check them out here.

What is the process for generating a record in the ContentDistribution object?

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.

Using Apex:

/* 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

);

Using Flow:

SIDENOTE: Alternatively, you have the option to utilize ContentAsset (for Asset files) to make the file publicly accessible. However, it’s worth noting that this approach is slightly more intricate than the one outlined above!

I hope you find this information valuable. Stay tuned for the next one! A big thank you for being an amazing reader! Subscribe to ForcePanda to receive all the latest updates directly in your inbox.