File Preview and Download Using LWC

You will learn the following things

  1. Component Creation
  2. Fetching file Details by sending recordId to Apex
  3. Rendering Data and making it Downloadable
  4. Preview of file on button click
  5. Navigation in LWC

Video Tutorial


Code

  1. Create Lwc component filePreviewAndDownloads and add the following code to the respective files.
filePreviewAndDownloads.html
<template>
    <lightning-card title="File Preview and Download">
         <template for:each={filesList} for:item="file">
             <div key={file.value} class="slds-box">
                 <div class="slds-grid slds-wrap">
                     <div class="slds-col slds-large-size_4-of-12 slds-medium-size_4-of-12 slds-size_12-of-12">
                       <p><strong>FileName - </strong>{file.label}</p>
                     </div>
                     <div class="slds-col slds-large-size_4-of-12 slds-medium-size_4-of-12 slds-size_12-of-12">
                       <a href={file.url} download>Download</a>
                     </div>
                     <div class="slds-col slds-large-size_4-of-12 slds-medium-size_4-of-12 slds-size_12-of-12">
                       <lightning-button label="Preview" 
                       variant="brand"
                      data-id={file.value}
                      onclick={previewHandler}
                       ></lightning-button>
                     </div>
                   </div>
             </div>
         </template>
    </lightning-card> 
    
 </template>
filePreviewAndDownloads.js
import { LightningElement, api, wire } from 'lwc';
import getRelatedFilesByRecordId from '@salesforce/apex/filePreviewAndDownloadController.getRelatedFilesByRecordId'
import {NavigationMixin} from 'lightning/navigation'
export default class FilePreviewAndDownloads extends NavigationMixin(LightningElement) {

    @api recordId='0010o00002ng22vAAA'
    filesList =[]
    @wire(getRelatedFilesByRecordId, {recordId: '$recordId'})
    wiredResult({data, error}){ 
        if(data){ 
            console.log(data)
            this.filesList = Object.keys(data).map(item=>({"label":data[item],
             "value": item,
             "url":`/sfc/servlet.shepherd/document/download/${item}`
            }))
            console.log(this.filesList)
        }
        if(error){ 
            console.log(error)
        }
    }
    previewHandler(event){
        console.log(event.target.dataset.id)
        this[NavigationMixin.Navigate]({ 
            type:'standard__namedPage',
            attributes:{ 
                pageName:'filePreview'
            },
            state:{ 
                selectedRecordId: event.target.dataset.id
            }
        })
    }
}
filePreviewAndDownloads.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>
  1. Create an Apex class filePreviewAndDownloadController.cls and add the following code to the file.
filePreviewAndDownloadController.cls
public with sharing class filePreviewAndDownloadController {
    @AuraEnabled(cacheable=true)
        public static Map<ID, String> getRelatedFilesByRecordId(String recordId) {
            // Get record file IDs        
            List<ContentDocumentLink> files = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :recordId];
            List<ID> fileIDs = new List<ID>();
            for (ContentDocumentLink docLink : files) {
                fileIDs.add(docLink.ContentDocumentId);
            }
     
            List<ContentVersion> docs = [SELECT ContentDocumentId, FileExtension, Title 
                FROM ContentVersion WHERE ContentDocumentId IN : fileIDs];
            Map<ID, String> mapIdTitle = new Map<ID, String>();
            for (ContentVersion docLink : docs) {
                mapIdTitle.put(docLink.ContentDocumentId, docLink.Title);
            }
            return mapIdTitle;
        }
}

Final Output

Now place your component to the record page. You will see the following output

Fig:1 filePreviewAndDownloads component after pacing on the page
Fig:1 filePreviewAndDownloads component after pacing on the page


Site developed by Nikhil Karkra © 2024 | Icons made by Freepik