
Dynamically Open Salesforce Files or ContentDocument In Lightning Component
Hi guys today in this post we are going to learn, how we can open or display a preview of contentDocument or salesforce files dynamically in salesforce lightning component using <lightning:fileCard> base component. A <lightning:fileCard> component displays a preview of a file (Image, Text, PDF…etc.). On desktops, clicking the file preview opens the SVG file preview player, enabling you to preview images, documents, and other files in the browser. The file preview player provides quick access to file actions, such as upload, delete, download, and share. On mobile devices, clicking the file preview downloads the file. The file type determines the icon used on the file preview and caption area.
So In this post we will create a component to display list of all available salesforce files records and on clicking on the file title we will display a preview of file.
Step 1. Apex Controller [fileViewerCtrl.apxc]
public class fileViewerCtrl { @AuraEnabled public static List<contentDocument> fetchContentDocument(){ return [Select id,Title,FileType,CreatedBy.Name,ContentSize From contentDocument LIMIT 1000]; } }
Step 2 : Lightning Component [filePreviewer.cmp]
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="fileViewerCtrl"> <!--aura doInit handler--> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <!--aura attributes--> <aura:attribute name="selectedDocumentId" type="string"/> <aura:attribute name="lstContentDoc" type="List"/> <aura:attribute name="hasModalOpen" type="boolean" default="false"/> <!-- Custom DataTable to Display List Of Available ContentDocuments Start--> <table class="slds-table slds-table_cell-buffer slds-table_bordered"> <thead> <tr class="slds-line-height_reset"> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Title">Title</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="File Type">File Type</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Created By">Created By</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="size">size(bytes)</div> </th> </tr> </thead> <tbody> <aura:iteration items="{!v.lstContentDoc}" var="CD"> <tr> <th scope="row"> <div class="slds-truncate" title="{!CD.Title}"> <!--store contentDocument Id in data-Id attribute--> <a onclick="{!c.getSelected}" data-Id="{!CD.Id}">{!CD.Title}</a> </div> </th> <th scope="row"> <div class="slds-truncate" title="{!CD.FileType}">{!CD.FileType}</div> </th> <th scope="row"> <div class="slds-truncate" title="{!CD.CreatedBy.Name}">{!CD.CreatedBy.Name}</div> </th> <th scope="row"> <div class="slds-truncate" title="{!CD.ContentSize}">{!CD.ContentSize}</div> </th> </tr> </aura:iteration> </tbody> </table> <!-- Custom DataTable to Display List Of Available ContentDocuments End--> <!--###### FILE PREVIEW MODAL BOX START ######--> <aura:if isTrue="{!v.hasModalOpen}"> <section onclick="{!c.closeModel}" role="dialog" aria-modal="true" class="slds-modal slds-fade-in-open"> <div class="slds-modal__container"> <div class="slds-modal__content slds-p-around_medium slds-text-align_center" style="background: transparent;"> <div style="width: 50%; margin: 0 auto; text-align: left"> <!--<lightning:fileCard> to preview file using content document Id --> <lightning:fileCard fileId="{!v.selectedDocumentId}"/> </div> </div> </div> </section> <div class="slds-backdrop slds-backdrop_open"></div> </aura:if> <!--###### FILE PREVIEW MODAL BOX END ######--> </aura:component>
JavaScript Controller : [filePreviewerController,js]
({ /*call apex controller method "fetchContentDocument" to get salesforce file records*/ doInit : function(component, event, helper) { var action = component.get("c.fetchContentDocument"); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { component.set('v.lstContentDoc', response.getReturnValue()); } else if (state === "INCOMPLETE") { // do something } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors[0] && errors[0].message) { console.log("Error message: " + errors[0].message); } } else { console.log("Unknown error"); } } }); $A.enqueueAction(action); }, getSelected : function(component,event,helper){ // display modle and set seletedDocumentId attribute with selected record Id component.set("v.hasModalOpen" , true); component.set("v.selectedDocumentId" , event.currentTarget.getAttribute("data-Id")); }, closeModel: function(component, event, helper) { // for Close Model, set the "hasModalOpen" attribute to "FALSE" component.set("v.hasModalOpen", false); component.set("v.selectedDocumentId" , null); }, })
Opening the file preview player is supported in Lightning Experience, the Salesforce mobile web, and Lightning communities.
Steps To Add Lightning Components as Custom Tabs in a Lightning Experience App
Lightning Component Files Preview :
Related Resources :
Other popular Post :
- Create Modal/Popup Box In Lightning Component – Salesforce
- Add Multiple Child Records to Parent Object With Lightning Component
- Download Data as CSV File With JavaScript In Salesforce Lightning Component
- Custom File Upload In Salesforce Lightning Component – Upload Large Attachments
- Formula Fields to Display Images From Content Documents – Salesforce Lightning/Classic
Like our facebook page for new post updates. & Don’t forget to bookmark this site for your future reference.
if you have any suggestions or issue with it, you can post in comment box.
Happy Learning
15 comments
Super. Thanks
Great article.
I am getting the follwoing error,while using the above code
Action failed: forceContent:fileCard$controller$onRenditionLoaded [Cannot read property ‘fire’ of undefined] Failing descriptor: {forceContent:fileCard$controller$onRenditionLoaded}
Can you let me know where did I went wrong .
are you using the same code ?
yes.
Hi Piyush
I am also getting the same error and using the same code..
This ‘lightning:fileCard’ component will only support in ‘Lightning Experience, Lightning Communities, Salesforce Mobile App’, might be you are testing this component with Standalone Lightning App.
Thank you for uploading such great features. Very helpful. Keep up the great work
Thank you SO much, It’s working Superbbb…!!!!!
Hi,
when I am clicking on preview button .its, not opening full screen. i used same code
Hi ,
Do you have any sample for content Search in files?
By using SOSL can we do a content search and show the files based on the search text.
Thanks
Hi, Can we disable/Hide download link?
Hi Can we disable or hide, Download, share and other actions showing in filepreview popup.
How can we display older versions of a content version like this in lightning component?
Hi,
I need to display all older versions of a content document in a lightning component. How can we do that?