Files in Salesforce

Hi Everyone,

In this post, I am going to show you how to download and Preview the files from Lightning Community using Lightning Web Component.

Before we get started, let’s discuss the Object Structure of the files to know how the files get stored into Salesforce.

Content Document: – Represents a document that has been uploaded to a library in Salesforce CRM Content or Salesforce Files.

Content Version: – Represents a specific version of a document in Salesforce CRM Content or Salesforce Files. One Content Document can have multiple content versions.

Content Document Link:- Represents the link between a Salesforce CRM Content document or Salesforce file and where it’s shared. A file can be shared with other users, groups, records, and Salesforce CRM Content libraries.

Here is the complete diagram.

Files in Salesforce

This is how your component will look like once you have completed the development of the component.


  1. Preview the Files in both Lightning Experience and Lighting Community
  2. Download the Files in both Lightning Experience and Lighting Community
  3. Delete the files
  4. Upload new files under the same record
  5. Filter the files based on created date and file title
  6. Sync the files from Salesforce if the file has been uploaded from a different place.
  7. Control what information needs to show in the table.


  1. The only limitation of the component is, we can use it under the record detail page only.

Use Component inside Salesforce Record Page in Lightning Experience

To use the component, Open the record detail page of any object where you wanted to use this component. Click on gear icon and then click on Edit page.

In the left, search for content manager, drag and drop the component where you wanted to place.

It requires some additional information that your salesforce admin can setup. See below screenshot

Setup Component in Lighting Experience
  1. Title: – Title of the Lighting Card
  2. Record Id: – use recordId as value for Lighting Experience and {!recordId} if component is used in Lightning Community
  3. Do you want to show Details? – to display the file details. Keep as true
  4. Accepted file format to upload the files? – It has some default values. if you wanted to remove or add make the adjustment.
  5. User Can Sync the files from Salesforce? – If true it will show a button to sync the files from salesforce.
  6. Do you want the users to upload the new files? – If true, the user will be able to see the upload button.
  7. The component is used in the community? – Check this as true if the component is being used in the Salesforce Community.
  8. Show Filters? – If true, the user will be able to see the filters.

Let’s setup the code.

Create the Apex Class.

 * @description       : 
 * @author            : Amit Singh
 * @group             : 
 * @last modified on  : 12-02-2020
 * @last modified by  : Amit Singh
 * Modifications Log 
 * Ver   Date         Author       Modification
 * 1.0   11-26-2020   Amit Singh   Initial Version
public with sharing class ContentManagerService {
    public static String getContentDetails(String recordId) {
        List<ContentDocumentLink> contentDocumentList = [SELECT ContentDocumentId, LinkedEntityId 
                                                            FROM   ContentDocumentLink 
                                                            WHERE  LinkedEntityId =: recordId];
        Set<Id> contentDocumentId = new Set<Id>();
        for(ContentDocumentLink cdl : contentDocumentList){
        List<ContentVersion> contentVersionList = [SELECT Id, VersionData, FileType, Title, FileExtension,
                                                    ContentDocument.CreatedBy.Name, ContentDocument.ContentSize,
                                                    CreatedDate, ContentDocumentId, ContentDocument.FileType
                                                    FROM   ContentVersion 
                                                    WHERE  ContentDocumentId IN : contentDocumentId];
        return JSON.serialize(contentVersionList);

    public static void deleteContentDocument(String recordId) {

    public static string ContentType(String fileType) {

        switch on fileType.toLowerCase(){
            when 'docx' {
                return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            when 'csv' {
                return 'application/';
            when 'wav' {
                return 'audio/wav';
            when 'wmv' {
                return 'video/x-ms-wmv';
            when 'mp3' {
                return 'audio/mpeg';
            when 'mp4' {
                return 'video/mp4';
            when 'png' {
                return 'image/png';
            when 'pdf' {
                return 'application/pdf';
            when else {
                return 'image/jpeg';


Create the Lightning Web Component and use below code.

Code for HTML file

    @description       : 
    @author            : Amit Singh
    @group             : 
    @last modified on  : 12-02-2020
    @last modified by  : Amit Singh
    Modifications Log 
    Ver   Date         Author       Modification
    1.0   11-26-2020   Amit Singh   Initial Version
    <lightning-card  variant="Narrow"  title={title} icon-name="standard:document">
        <template if:true={isLoading}>
            <lightning-spinner alternative-text="Loading" size="small" variant="brand"></lightning-spinner>
        <lightning-button if:true={showsync} variant="brand" title="Content Sync" icon-name="utility:sync"
            onclick={handleSync} slot="actions" >
        <div class="slds-var-p-around_small" >
            <div class="slds-grid slds-wrap">
                <div class="slds-col slds-size_1-of-4" if:true={showFilters}>
                    <lightning-input if:true={showFilters} type="search" variant="standard" name="Title" label="Title" onchange={handleSearch} >
                <div class="slds-col slds-size_1-of-4" if:true={showFilters}>
                    <lightning-input  if:true={showFilters} type="search" variant="standard" name="Created By" label="Created By" onchange={handleSearch}>\
                <div class="slds-col slds-size_2-of-4 slds-var-p-left_small">
                    <lightning-file-upload  if:true={showFileUpload}
                        label="Upload New File"
        <div class="slds-var-p-around_small">

Code for javascript files.

import { api, LightningElement, track, wire } from 'lwc';
import getContentDetails from '@salesforce/apex/ContentManagerService.getContentDetails';
import deleteContentDocument from '@salesforce/apex/ContentManagerService.deleteContentDocument';
import { NavigationMixin } from 'lightning/navigation';

const columns = [
    { label: 'Title',       fieldName: 'Title', wrapText : true,
        cellAttributes: { 
            iconName: { fieldName: 'icon' }, iconPosition: 'left' 
    { label: 'Created By',  fieldName: 'CREATED_BY',
        cellAttributes: { 
            iconName: 'standard:user', iconPosition: 'left' 
    { label: 'File Size',   fieldName: 'Size' },
    { label: 'Preview', type:  'button', typeAttributes: { 
            label: 'Preview',  name: 'Preview',  variant: 'brand-outline',
            iconName: 'utility:preview', iconPosition: 'right'
    { label: 'Download', type:  'button', typeAttributes: { 
            label: 'Download', name: 'Download', variant: 'brand', iconName: 'action:download', 
            iconPosition: 'right' 
    { label: 'Delete', type:  'button', typeAttributes: { 
            label: 'Delete',   name: 'Delete',   variant: 'destructive',iconName: 'standard:record_delete', 
            iconPosition: 'right' 

export default class ContentManager extends NavigationMixin(LightningElement) {

    @api title;
    @api showDetails;
    @api showFileUpload;
    @api showsync;
    @api recordId;
    @api usedInCommunity;
    @api showFilters;
    @api accept = '.csv,.doc,.xsl,.pdf,.png,.jpg,.jpeg,.docx,.doc';

    @track dataList;
    @track columnsList = columns;
    isLoading = false;


    connectedCallback() {

        let baseUrl = 'https://''/';
        return baseUrl;


        const actionName =;
        const row = event.detail.row;
        switch (actionName) {
            case 'Preview':
            case 'Download':
            case 'Delete':


                type: 'standard__namedPage',
                attributes: {
                    pageName: 'filePreview'
                state : {
                    selectedRecordId: file.ContentDocumentId
        } else if(this.usedInCommunity){
                type: 'standard__webPage',
                attributes: {
                    url: file.fileUrl
            }, false );

                type: 'standard__webPage',
                attributes: {
                    url: file.downloadUrl
            }, false 


        this.isLoading = true;

            recordId : row.ContentDocumentId
        .then(result => {
            this.dataList  = this.dataList.filter(item => {
                return item.ContentDocumentId !== row.ContentDocumentId ;
        .catch(error => {
            console.error('**** error **** \n ',error)
            this.isLoading = false;


        let imageExtensions = ['png','jpg','gif'];
        let supportedIconExtensions = ['ai','attachment','audio','box_notes','csv','eps','excel','exe',

        this.isLoading = true;
            recordId : this.recordId
        .then(result => {
            let parsedData = JSON.parse(result);
            let stringifiedData = JSON.stringify(parsedData);
            let finalData = JSON.parse(stringifiedData);
            let baseUrl = this.getBaseUrl();
            finalData.forEach(file => {
                file.downloadUrl = baseUrl+'sfc/servlet.shepherd/document/download/'+file.ContentDocumentId;
                file.fileUrl     = baseUrl+'sfc/servlet.shepherd/version/renditionDownload?rendition=THUMB720BY480&versionId='+file.Id;
                file.CREATED_BY  = file.ContentDocument.CreatedBy.Name;
                file.Size        = this.formatBytes(file.ContentDocument.ContentSize, 2);

                let fileType = file.ContentDocument.FileType.toLowerCase();
                    file.icon = 'doctype:image';
                        file.icon = 'doctype:' + fileType;
            this.dataList = finalData;
        .catch(error => {
            console.error('**** error **** \n ',error)
            this.isLoading = false;

    formatBytes(bytes,decimals) {
        if(bytes == 0) return '0 Bytes';
        var k = 1024,
            dm = decimals || 2,
            sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];

        let value =;
        let name  =;
        if( name === 'Title' ){
            this.dataList = this.dataList.filter( file => {
                return file.Title.toLowerCase().includes(value.toLowerCase());
        } else if( name === 'Created By' ){
            this.dataList = this.dataList.filter( file => {
                return file.CREATED_BY.toLowerCase().includes(value.toLowerCase());

Code for meta.xml file

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="">
    <masterLabel>Content Manager</masterLabel>
    <!-- Configuring the design attributes -->
        <targetConfig targets="lightning__RecordPage, lightningCommunity__Default">
            <property name="title" type="String" label="Title" default="Content Manager" required="true"/>
            <property name="recordId" type="String" default="recordId" label="Record Id" required="true"/>
            <property name="showDetails" type="Boolean" default="true" label="Do you want to Show Details ?"/>
            <property name="accept" type="String" default=".csv,.doc,.xsl,.pdf,.png,.jpg,.jpeg,.docx,.doc" 
                    label="User can upload the files in format?" />
            <property name="showsync" type="Boolean" default="true" label="User can sync the files from Salesforce?" />
            <property name="showFileUpload" type="Boolean" default="true" label="Do you want the users to upload a new file ?"/>
            <property name="usedInCommunity" type="Boolean" default="false" label="Component is used in Community?" />
            <property name="showFilters" type="Boolean" default="true" label="Show Filters?" />

Deploy the code to your salesforce org and Enjoy.

Thanks for reading 🙂

#HappyReading #DeveloperGeeks #AskPanther #SFDCPanther

Our Score
Click to rate this post!
[Total: 1 Average: 5]

17 thoughts on “How to preview files in Lightning Community using LWC”

  1. Hello Panther, is there any possibility we can developer same UI, based on External links(Video,Image,png) using LWC or Lightning. the feature need to have like zoom in/out, option also?

  2. Hello sir,
    How to create new folder(with folder icon) using apex class in lightning web component.
    When clicking foder icon then their input field folder name when enter name of folder then cliking on save button then save in database.

  3. Thank you! Save me a bunch of development time.
    I had to tweak it a little (add a parameter to xml to adapt baseUrl) to handle preview&download for Community: it didn’t properly work in our multiple-community org. Would you happen to know a more robust way to download files rather than the semi-hardcoded url used here?

      1. That is a bit odd but, for us, the {}/sfc/servlet.shepherd/document/download/{ContentDocumentId} results in a community error and I had to add a in-between parameter to get {}/{communityName}/sfc/servlet.shepherd/document/download/{ContentDocumentId}.
        No big deal anyway, everything else is perfect.

  4. Hi, i have troubles with the visibility of Files.
    I only see files i own. Also as Administrator.
    I think that because of the visibility flag on the ContentDocument Object.
    How did you solve this problem?

    As a service employee i want to see all Files on a Case not only the files i uploaded.

Leave a Reply