How To Preview and Download Files Using LWC?

How To Preview and Download Files Using LWC?


In this blog, you will learn how you can preview and download files from salesforce using lightning web component.

Source Code

LWC.html

<template>
    <lightning-card title="File Preview and Download" icon-name="standard:file">
        <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_6-of-12 slds-medium-size_6-of-12 slds-size_12-of-12">
                      <p><strong>Filename - </strong>{file.label}</p>
                    </div>
                    <div class="slds-col slds-large-size_6-of-12 slds-medium-size_6-of-12 slds-size_12-of-12">
                        <div class="slds-button-group" role="group">
                             <lightning-button label="Preview" variant="neutral" data-id={file.value} onclick={previewHandler}
                            ></lightning-button>
                            <a href={file.url} class="slds-button slds-button_neutral" download>Download</a>
                          </div>                    
                    </div>
                  </div>
            </div>
        </template>
   </lightning-card>
</template>


LWC.JS

import { LightningElement, api, wire } from 'lwc';
import getRelatedFilesByRecordId from '@salesforce/apex/FileController.getRelatedFilesByRecordId'
import {NavigationMixin} from 'lightning/navigation'

export default class FileDownloadPreview extends NavigationMixin(LightningElement) {

    @api recordId;
    filesList =[];
    @wire(getRelatedFilesByRecordId, {recordId: '$recordId'})
    wiredResult({data, error}){
        if(data){
            this.filesList = Object.keys(data).map(item=>({"label":data[item],
             "value": item,
             "url":'/sfc/servlet.shepherd/document/download/'+ item
            }))
        }
        if(error){
            console.log(error);
        }
    }
    previewHandler(event){
        this[NavigationMixin.Navigate]({
            type:'standard__namedPage',
            attributes:{
                pageName:'filePreview'
            },
            state:{
                selectedRecordId: event.target.dataset.id
            }
        })
    }
}


LWC.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>


FileController.cls

public with sharing class FileController {
    @AuraEnabled(cacheable=true)
    public static Map<ID, String> getRelatedFilesByRecordId(String recordId) {      
        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;
    }
}


Demo

0 Comments