How to get upload/delete and preview the files attachments through apex class uses of lightning:fileCard and lightning:fileUpload elements in Salesforce Lightning component | file Uploader With Preview & Delete in aura component Salesforce

5,364 views


Hey guys, In this post we are going to learn about How to get upload/delete and preview the files attachments through apex class uses of lightning:fileCard and lightning:fileUpload elements in Salesforce Lightning component

Attach Files to Records

Attach files to records for a powerful way to collaborate and stay organized in Salesforce. Keep information on an opportunity, account, case or sObject (Custom Object) right where you need it. Share relevant documents with anyone with access to the record. To know more details about Attach Files to Records, click Here.

Requirement:- Upload the custom file on lightning component such like (jpg’, β€˜jpeg’,’pdf’, β€˜doc’) etc.. then iterate the list of attachment record and get preview (zoom), delete file dynamically.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
   

Files we used to Preview & Delete aura component in this post example

UploadFileCmp.cmp Lightning Component It is used for create the table of Preview & Delete attachment file in aura component.
UploadFileCmpController.js JavaScript Controller File It is used for communicate to server side apex method and fetch list of file and attachment from salesforce object.
UploadFileCmpHelper.js JavaScript Helper File It is hold for Javascript Helper Function to get file & attachment from apex method.
UploadFileCmp.css Style CSS It is used to create a content box border color and alignment.
uploadFileHandler.apxc Apex Class Controller It is used for fetch the attachment files from sObject in Salesforce.

Standard Object:- ContentDocument

Object and their fields:- LinkedEntityId, ContentDocumentId, Title, FileType

Final Output

upload delete and preview files attachments lightning component -- w3web.net

 

You can download file directly from github by Click Here.

 
 

Other related post that would you like to learn in Salesforce

  • Find the below steps

Create Lightning Component

Step 1:- Create Lightning Component : UploadFileCmp.cmp

From Developer Console >> File >> New >> Lightning Component

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
   

UploadFileCmp.cmp [Lightning Component File]

  1.    <aura:component controller="uploadFileHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
  2.     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
  3.     <aura:attribute name="files" type="ContentDocument[]"/>  
  4.     <aura:attribute name="recordId" type="string" default=""/>  
  5.     <aura:attribute name="accept" type="List" default="['.jpg', '.jpeg','.pdf','.csv','.xlsx']"/>  
  6.     <aura:attribute name="multiple" type="Boolean" default="true"/>      
  7.     <aura:attribute name="Spinner" type="boolean" default="false"/>
  8.  
  9.     <lightning:card>
  10.         <div class="slds">  
  11.             <lightning:notificationsLibrary aura:id="notifLib"/>
  12.             <div class="contentbox">  
  13.                 <div class="slds-page-header header">Files ({!v.files.length})</div>  
  14.                 <div class="slds-grid">  
  15.                     <div style="width:100%">  
  16.                         <center>
  17.                             <lightning:fileUpload label="" multiple="{!v.multiple}"   
  18.                                                   accept="{!v.accept}" recordId="{!v.recordId}"   
  19.                                                   onuploadfinished="{!c.UploadFinished}" />  
  20.                         </center>
  21.                     </div>  
  22.                 </div><br/> 
  23.                 <div class="slds-form--compound" style="position:relative">
  24.                     <table class="slds-table slds-table--bordered">  
  25.                         <thead>  
  26.                             <tr>  
  27.                                 <th></th>
  28.                                 <th>Title</th>  
  29.                                 <th>FileType</th>                    
  30.                             </tr>  
  31.                         </thead>  
  32.                         <tbody>
  33.                             <aura:iteration items="{!v.files}" var="f">  
  34.                                 <tr>  
  35.                                     <td><a href="javascript:void(0)" id="{!f.Id}" onclick="{!c.delFilesAction}">Delete</a></td>
  36.                                     <td><a href="" id="{!f.Id}" onclick="{!c.previewFileAction}">{!f.Title}</a></td>  
  37.                                     <td>{!f.FileType}</td>                              
  38.                                 </tr>  
  39.                             </aura:iteration>  
  40.                         </tbody>  
  41.                     </table>  
  42.                     <aura:if isTrue="{!v.Spinner}">
  43.                         <div class="slds-spinner_container">
  44.                             <div class="slds-spinner slds-spinner--medium" aria-hidden="false" role="alert">
  45.                                 <div class="slds-spinner__dot-a"></div>
  46.                                 <div class="slds-spinner__dot-b"></div>
  47.                             </div>
  48.                         </div>
  49.                     </aura:if>
  50.                 </div>
  51.             </div>  
  52.            <br/>
  53.             <br/>
  54.    <!--Start RelatedTopics Section-->
  55. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  56.  
  57.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  58.  
  59.             <br/><br/>
  60.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like β†’</span> </strong></p>
  61.             <div style="display:block; overflow:hidden;"> 
  62.                 <div style="width: 50%; float:left; display:inline-block">
  63.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  64.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  65.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  66.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  67.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  68.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  69.                     </ul>
  70.             </div>
  71.  
  72.             <div style="width: 50%; float:left; display:inline-block">
  73.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  74.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  75.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  76.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  77.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  78.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  79.                     </ul>
  80.                 </div>
  81.                <div style="clear:both;"></div> 
  82.                <br/>
  83.                 <div class="youtubeIcon">
  84.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  85.                 </div>
  86.     </div>
  87.  
  88. </div>
  89.  
  90.   <!--End RelatedTopics Section-->
  91.         </div>  
  92.     </lightning:card>      
  93. </aura:component>

Create JavaScript Controller

Step 2:- Create Lightning Component : UploadFileCmpController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

UploadFileCmpController.js [JavaScript Controller]

  1.   ({
  2. 	 doInit:function(component,event,helper){  
  3.        helper.getuploadedFiles(component);
  4.     },      
  5.  
  6.     previewFileAction :function(component,event,helper){  
  7.         var rec_id = event.currentTarget.id;  
  8.         $A.get('e.lightning:openFiles').fire({ 
  9.             recordIds: [rec_id]
  10.         });  
  11.     },  
  12.  
  13.     UploadFinished : function(component, event, helper) {  
  14.         var uploadedFiles = event.getParam("files");  
  15.         //var documentId = uploadedFiles[0].documentId;  
  16.         //var fileName = uploadedFiles[0].name; 
  17.         helper.getuploadedFiles(component);         
  18.         component.find('notifLib').showNotice({
  19.             "variant": "success",
  20.             "header": "Success",
  21.             "message": "File Uploaded successfully!!",
  22.             closeCallback: function() {}
  23.         });
  24.     }, 
  25.  
  26.     delFilesAction:function(component,event,helper){
  27.         component.set("v.Spinner", true); 
  28.         var documentId = event.currentTarget.id;        
  29.         helper.delUploadedfiles(component,documentId);  
  30.     }
  31. })

Create JavaScript Helper

Step 3:- Create Lightning Component : UploadFileCmpHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

UploadFileCmpHelper.js [JavaScript Helper File]

  1.   ({
  2. 	 getuploadedFiles:function(component){
  3.         var action = component.get("c.getFiles");  
  4.         action.setParams({  
  5.             "recordId":component.get("v.recordId")  
  6.         });      
  7.         action.setCallback(this,function(response){  
  8.             var state = response.getState();  
  9.             if(state=='SUCCESS'){  
  10.                 var result = response.getReturnValue();           
  11.                 component.set("v.files",result);  
  12.             }  
  13.         });  
  14.         $A.enqueueAction(action);  
  15.     },
  16.  
  17.     delUploadedfiles : function(component,documentId) {  
  18.         var action = component.get("c.deleteFiles");           
  19.         action.setParams({
  20.             "sdocumentId":documentId            
  21.         });  
  22.         action.setCallback(this,function(response){  
  23.             var state = response.getState();  
  24.             if(state=='SUCCESS'){  
  25.                 this.getuploadedFiles(component);
  26.                 component.set("v.Spinner", false); 
  27.             }  
  28.         });  
  29.         $A.enqueueAction(action);  
  30.     }, 
  31. })

Step 4:- Create Lightning Component Style: UploadFileCmp.css

From Developer Console >> File >> New >> Lightning Component >> Component Style CSS

UploadFileCmp.css [Style CSS]

  1.    .THIS .contentbox{
  2.     border-left: 1px solid #dddddd;  
  3.     border-right: 1px solid #dddddd;  
  4.     border-bottom: 1px solid #dddddd;  
  5.     border-top: 1px solid #dddddd;
  6.  }
  7.  
  8.  .THIS .header{
  9.     border-radius: 0px; 
  10.     border-right: 0px;
  11.     border-left: 0px;
  12.     border-top: 0px;  
  13.     box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);
  14.  }

Create Apex Class Controller

Step 5:- Create Apex Class : uploadFileHandler.apxc

From Developer Console >> File >> New >> Apex Class

uploadFileHandler.apxc [Apex Class Controller]

  1.    public class uploadFileHandler {
  2.    @AuraEnabled  
  3.     public static List<ContentDocument> getFiles(string recordId){        
  4.         Set<Id> recordIds=NEW Set<Id>{recordId};
  5.         Set<Id> documentIds = NEW Set<Id>(); 
  6.         List<ContentDocumentLink> cdl=[SELECT id,LinkedEntityId,ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId IN:recordIds];  
  7.         FOR(ContentDocumentLink cdLink:cdl){  
  8.             documentIds.add(cdLink.ContentDocumentId);  
  9.         }      
  10.         RETURN [SELECT Id,Title,FileType FROM ContentDocument WHERE id IN: documentIds];  
  11.     } 
  12.  
  13.     @AuraEnabled  
  14.     public static void deleteFiles(string sdocumentId){ 
  15.         DELETE [SELECT Id,Title,FileType FROM ContentDocument WHERE id=:sdocumentId];       
  16.     }  
  17. }

upload delete and preview files attachments lightning component -- w3web.net

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

What is the difference between file and attachment in Salesforce?

Files need to upload, store, share, and collaborate on Salesforce files in the cloud. Attach files to records from the Attachments related list on selected detail pages. We can upload a file and store it privately until you're ready to share it.

Where are Salesforce attachments?

Attachments appear in the Notes & Attachments Related List. Salesforce Files use ContentVersion records which are then associated with a parent record.

How do I convert attachments in Salesforce?

we need to insert the new file record into Salesforce. But if we insert the new record we can lose Created Date, LastModified Date, CreatedById, and Last Modified By Id.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses β†’

πŸ‘‰ Get Free Course β†’

πŸ“Œ Salesforce Administrators

πŸ“Œ Salesforce Lightning Flow Builder

πŸ“Œ Salesforce Record Trigger Flow Builder

πŸ‘‰ Get Free Course β†’

πŸ“Œ Aura Lightning Framework

πŸ“Œ Lightning Web Component (LWC)

πŸ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment