Generate Public URL for Salesforce Files

by Rijwan Mohmmed
generate-public-url-for-salesforce files-techdicer

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.

generate-public-url-for-salesforce files-public-lin-button-techdicer
generate-public-url-for-salesforce files-public-lin-button-techdicer

2.By Apex :

GeneratePublicUrl.cls :

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 :

generate-public-url-for-salesforce files-output-techdicer

Reference :

  1. ContentDistribution
What’s your Reaction?

You may also like


Manjari February 6, 2023 - 4:27 am

Even if I am setting PreferencesAllowViewInBrowser = true I am not able to view the image. It says preview not available.

Rijwan Mohmmed February 6, 2023 - 12:45 pm

check rich-text field properly

Anirban Roy May 23, 2023 - 8:04 am

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]

Rijwan Mohmmed May 23, 2023 - 9:53 am

Yes I can help you. Book a meeting on my website.


Leave a Comment