+ Start a Discussion
jaishrijaishri 

In this below code account,contact and opportunity files on account page using lwc are displayed but files are not getting opened

<template>
   <lightning-card title="File" icon-name="standard : Files">
     <div class="slds‐m‐around_small">
      <template if:true={filesList}>
         <table class="slds-table slds-table_bordered slds-table_cell-buffer">
            <thead>
               <tr class="slds-text-title_caps">
                  <th scope="col">
                     <div title="Key">File Name</div>
                  </th>
                  <th scope="col">
                     <div title="Value">File Extension</div>
                  </th>
               </tr>
            </thead>
            <tbody>
               <template for:each={filesList} for:item="keyValue">
                  <tr key={keyValue.Id}>
                     <th scope="col">
                        <div>{keyValue.Title}</div>
                     </th>
                     <th scope="col">
                        <div>{keyValue.FileExtension}</div>
                     </th>
                  </tr>
               </template>
            </tbody>
         </table>
      </template>
      </div>
   </lightning-card>
</template>

import { LightningElement,api,wire } from 'lwc';
import queryFiles from '@salesforce/apex/filePreviewAndDownloadController.queryFiles'
export default class FileList extends LightningElement {
    @api recordId;
    wiredActivities;
    filesList =[];
    @wire(queryFiles, {recId: '$recordId'})
    wiredclass(value){
        this.wiredActivities = value;
        const { data, error } = value;
        if (data) {
            console.log(data)
            this.filesList = data;
            console.log('Data========> '+JSON.stringify(this.filesList));
        }
        if(error){
            console.log(error);
        }
    }
}
   

public with sharing class filePreviewAndDownloadController {
    @AuraEnabled(cacheable = true)
    public Static  List<ContentVersion> queryFiles(String recId){
        set<Id> SetIds = new Set<id>();
        list<Account> lstAccount = [Select Id,(Select Id From Contacts),(Select Id From Opportunities) from Account where Id = :recId];
        for(Account Acc : lstAccount){
            SetIds.add(Acc.Id);
            for(Contact con : Acc.Contacts){
            SetIds.add(con.Id);
            }
            for(Opportunity opp : Acc.Opportunities){
            SetIds.add(opp.Id);
            }
        }
           List<ContentDocumentLink> files = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :SetIds];
            List<ID> fileIDs = new List<ID>();
            for (ContentDocumentLink docLink : files) {
                fileIDs.add(docLink.ContentDocumentId);
            }
            List<ContentVersion> docs = [SELECT Id,ContentDocumentId, FileExtension, Title
                                         FROM ContentVersion WHERE ContentDocumentId IN :fileIDs];
         
            return docs;
    }
}
 
Best Answer chosen by jaishri
CharuDuttCharuDutt
Hii JayS
Try Below Code
<template>
    <lightning-card title="File Preview" icon-name="custom:custom11">
      <div class="slds‐m‐around_small">
       <template if:true={filesList}>
          <table class="slds-table slds-table_bordered slds-table_cell-buffer">
             <thead>
                <tr class="slds-text-title_caps">
                   <th scope="col">
                      <div title="Key">File Name</div>
                   </th>
                   <th scope="col">
                      <div title="Value">File Extension</div>
                   </th>
                </tr>
             </thead>
             <tbody>
                <template for:each={filesList} for:item="keyValue">
                   <tr key={keyValue.Id}>
                      <th scope="col">
                         <div>{keyValue.Title}</div>
                      </th>
                      <th scope="col">
                         <div>{keyValue.FileExtension}</div>
                      </th>
                      <th scope="col">
                         <lightning-button data-id={keyValue.ContentDocumentId}
                            access-key={keyValue.Title} 
                            icon-name="utility:preview"
                            label="Preview" 
                            variant="brand" 
                            value={keyValue.FileExtension}
                            onclick={filePreview}></lightning-button>
                      </th>
                   </tr>
                </template>
             </tbody>
          </table>
       </template>
       </div>
       <template if:true={ShowTable}>
          <div class="slds-box slds-theme_shade">
             <div class="slds-modal slds-fade-in-open slds-backdrop">
                <div class="slds-modal__container">
                   <!--HEADER Section-->  
                   <div class="slds-modal__header">
                      <lightning-button-icon icon-name="utility:close" alternative-text="Close this window" size="large"  
                         variant="bare-inverse" onclick={closeModal} class="slds-modal__close">  
                      </lightning-button-icon>
                      <h2>CSV File Details</h2>
                   </div>
                   <!---Body Section-->  
                   <div class="slds-modal__content slds-p-around_medium">
                      <table class="slds-table slds-table_bordered slds-table_cell-buffer">
                         <thead>
                            <tr class="slds-text-title_caps">
                               <template for:each={csvTableHeader} for:item="header">
                                  <th class="" scope="col" key={header}>
                                     <div class="slds-truncate" title={header}>{header}</div>
                                  </th>
                               </template>
                            </tr>
                         </thead>
                         <tbody>
                            <template for:each={lstCsvTableData} for:item="obj" for:index="Idx">
                               <tr class="slds-hint-parent" key={obj.rowIndx}>
                                  <template for:each={obj.data} for:item="Rec">
                                     <td key={Rec}>
                                        <div class="slds-truncate" title={Rec}>{Rec}</div>
                                     </td>
                                  </template>
                               </tr>
                            </template>
                         </tbody>
                      </table>
                   </div>
                   <!-- Section
                      <div class="slds-modal__footer">  
                        </div>
                      -->     
                </div>
             </div>
          </div>
       </template>
    </lightning-card>
 </template>


##############################################################################################################

JS


import { LightningElement,api,wire } from 'lwc';
import cvRecords2 from '@salesforce/apex/contenVersionFilePreview.cvRecords2'
import readCsvData from '@salesforce/apex/contenVersionFilePreview.readCsvData'
import {NavigationMixin} from 'lightning/navigation'
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
import { deleteRecord } from 'lightning/uiRecordApi';
let lstCsvData = [];
let lstLowercaseHeader = [];
let lstNewTrimCsvData = [];
let lstAllCopyRecords = [];
let lstHeader = [];
export default class ContentVersionFilePreview extends  NavigationMixin(LightningElement) {
    @api recordId;
    csvTableHeader = [];  
    ShowTable = false;
    lstCsvTableData = [];
    dwnldVal;
    url;
    wiredActivities;
    ShowTable = false;
    filesList =[];

    closeModal(){
        this.ShowTable= false;
    }

    @wire(cvRecords2, {recId: '$recordId'})
    wiredclass(value){
        this.wiredActivities = value;
        const { data, error } = value;
        if (data) { 
            console.log(data)
            this.filesList = data;
            /*for(var i=0;i<data.length;i++){
                var h = '/sfc/servlet.shepherd/document/download/'+data[i].Id+'?operationContext=S1';

        
        this.url = encodeURI(h);
            }*/
            console.log('Data========> '+JSON.stringify(this.filesList));
        }
        if(error){ 
            console.log(error);
        } 
    }
 
    filePreview(event) {
       const fileName =event.target.accessKey;
	   const fileExten = event.target.value;
       const RecId = this.recordId;
       var mapOfCsv = new Map();
       this.lstCsvTableData = [];
       var convertCsvHeaderInLowrcase = [];
       var convertObjIntoPlainObj = [];
	   if(fileExten == 'csv'){
        readCsvData({recId: RecId,fileName:fileName})
        .then((result) => {
            var lstRows = result.split("\n");
                          var withoutBlankRow = [];
                          for(var i=0; i<lstRows.length; i++){
                              if(lstRows[i] != ''){
                                withoutBlankRow.push(lstRows[i]);
                              }
                          }
                        

                           var storeCsvHeader = withoutBlankRow[0].split(",");
                          let lstTrimHeader = [];
                          for(var i=0; i<storeCsvHeader.length; i++){
                              if(storeCsvHeader[i].trim() != ''){
                                  
                            lstTrimHeader.push(storeCsvHeader[i].trim());
                            convertCsvHeaderInLowrcase.push((storeCsvHeader[i].trim()).toLowerCase());
                          }
                        }
                          lstLowercaseHeader = convertCsvHeaderInLowrcase;
                       
                          this.ShowTable = true;
                          this.csvTableHeader = lstTrimHeader;
    
                             
                         lstCsvData = [];
                         console.log('withoutBlankRow : ' + JSON.stringify(withoutBlankRow));
                           for(var i=1; i< (withoutBlankRow.length); i++){
                               var lstEachRowData = withoutBlankRow[i].split(",");
                            console.log('lstEachRowData : ' + lstEachRowData);
                               let csvTrimData = [];
                               for(var j=0; j< lstTrimHeader.length; j++){
                                   csvTrimData.push(lstEachRowData[j].trim());
                                mapOfCsv.set(lstTrimHeader[j],lstEachRowData[j].trim());
                                
                              }
                              
                             let obj = Object.fromEntries(mapOfCsv.entries());
                            
                             convertObjIntoPlainObj.push(obj);
                            lstCsvData.push({ 'rowIndx' : i.toString(),
                                              'data' :csvTrimData,
                                              'isChecked' : false });
                              
                           }
                           lstNewTrimCsvData = convertObjIntoPlainObj;
                           
                           this.lstCsvTableData = lstCsvData;
           console.log('CSV=====> '+JSON.stringify(result));
        })
        .catch((error)=>{
            console.log('CSVE=====> '+error);
    });
       }else{
            this[NavigationMixin.Navigate]({
                type: 'standard__namedPage',
                attributes: {
                    pageName: 'filePreview'
                },
                state : {
                   
                    selectedRecordId:event.currentTarget.dataset.id
                }
              })
	   }
    }
}

#############################################################################################################

Apex


public class contenVersionFilePreview {
    @AuraEnabled(cacheable = true)
    public Static  List<ContentVersion> cvRecords2(String recId){
        set<Id> SetIds = new Set<id>();
        list<Account> lstAccount = [Select Id,(Select Id From Contacts),(Select Id From Opportunities) from Account where Id = :recId];
        for(Account Acc : lstAccount){
            SetIds.add(Acc.Id);
            for(Contact con : Acc.Contacts){
            SetIds.add(con.Id);
        	}
            for(Opportunity opp : Acc.Opportunities){
            SetIds.add(opp.Id);
        	}
        }
           List<ContentDocumentLink> files = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :SetIds];
            List<ID> fileIDs = new List<ID>();
            for (ContentDocumentLink docLink : files) {
                fileIDs.add(docLink.ContentDocumentId);
            }
            List<ContentVersion> docs = [SELECT Id,ContentDocumentId, FileExtension, Title 
                						 FROM ContentVersion WHERE ContentDocumentId IN :fileIDs];
          
            return docs;// return [SELECT Id,ContentDocumentId, FileExtension,VersionData , Title FROM ContentVersion];
                						 
      
    }
}
Please Mark It As Best Answer If It Helps
Thank You!