Hello friends, today we are going to discuss How to Generates Public URLs for Salesforce Files. So we can show these files without salesforce login.
Also check this: Create Reusable Dependent Picklist in LWC
You can handle this very efficiently with Salesforce by using the Content Delivery object; API Name: ContentDistribution.
Creating a record on the ContentDistribution object with a link to the respective ContentVersion Id is sufficient for exposing a file publicly.
Two fields are automatically populated when you create a record of the ContentDistribution type, namely DistributionPublicUrl and ContentDownloadUrl.
DistributionPublicUrl link can be preview and there is a download link so you can also download this.
Process :
There are two options that you can create this
Manually Way : you need to go files and open any file there is a button named “Public link” click on this and we can get a public link and share to another user.

2.By Apex :
GeneratePublicUrl.cls :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class GeneratePublicUrl { public static void generatePublicLink(Id contentDocumentId){ /* Getting ContentVersion file using ContentDocument Id */ ContentVersion cv = [SELECT Id, Title FROM ContentVersion WHERE ContentDocumentId = :contentDocumentId]; /* Creating ContentDistribution record */ ContentDistribution conDis = new ContentDistribution(); conDis.Name = cv.Title; conDis.ContentVersionId = cv.Id; conDis.PreferencesAllowViewInBrowser= true ; insert conDis; } } |
Output :

4 comments
Even if I am setting PreferencesAllowViewInBrowser = true I am not able to view the image. It says preview not available.
check rich-text field properly
Hi Sir, Can you help to store file as Blog from Site Guest User? I’m getting this error, no matter how I insert. I tried to convert it to attachment and then to Content document, still the same issue.
INVALID_STATUS, Documents in a user’s private library must always be owned by that user.: [OwnerId]
Yes I can help you. Book a meeting on my website.