Use Salesforce files (image file) on LWC, Aura or VF page as img tag

enter image description here

Salesforce Files had been introduced with replacement of Attachment/Document object and with some great features like version controlling, sharing, preview and what not.

We used to use Attachment/Document object for file hosting like images and pdf (specially on Classic).

And if we needed to use that image on any VF page or AURA component, we simply use record id and below code to generate url:


But with Salesforce Files object, we have to maintain 3 records in 3 different objects “ContentDocument, ContentVersion, ContentLink” and for Public Link =”ContentDistribution”.

If you’re going to use your custom component/vf page internally, then you can use below code:

imageURL='/sfc/servlet.shepherd/document/download/<YOUR FILE ID>';

But when you need it to be visible for guest users, then you’ll need to generate PUBLIC URL which you can do manually.

Generating Public Link:

Code below will generate public url automatically. You can use this code on a trigger on Files object

ContentDocumentLink cdl = [select, contentdocument.title, contentdocument.filetype from contentdocumentlink where linkedentityid = '<Opportunity Id>'];
ContentVersion cv = [select id from contentversion where contentdocumentid =];
ContentDistribution cd = new ContentDistribution();
cd.Name = 'Test';
cd.ContentVersionId =;
cd.PreferencesAllowViewInBrowser= true;
cd.PreferencesAllowOriginalDownload= true;
insert cd;

<img> tag URL Generation

Now the ContentDistribution object will store the public URL but it’ll contain the preview and we cannot use it as <img src> tag. Therefore we need actual image URL which you can get manually by properties of image and click “Copy image address”.

Below public link will be generated by code


Below correct link we need to use as <img> tag.

https://<domain><organization Id>&dpt=null&viewId=

Use following code to convert the public url to actual url we need.

List<Domain> domainList = [SELECT Domain FROM Domain];
                String domainString = domainList[0].Domain;
                String domainNameSubstring = domainString.substringBefore('.');
                String secondPart = domainNameSubstring.substringBefore('-');
                String firstPart = domainNameSubstring.substringAfter('-');
                String customDomainName = 'https://' + firstPart + '--' + secondPart + '';

Happy coding!

Sources :

Leave a Comment