How to display upload Image if a record existing an attachment in lightning component? | how to display image icon in lightning component from attachment

1,032 views

Hey guys, In this post we are going to learn about how to Display an Upload Icon on the lightning component if a object record has files or any kind of attachment..

Requirement:- If upload a custom file on lightning component such like (jpg’, ‘jpeg’,’pdf’, ‘doc’) etc.. then against of every record display should be an attachment Image on right side of table.

Files we used in this post example:-

fileAttachmentCmp.cmp Lightning Component It is used for display the name, address, email, and upload file button on the table.
fileAttachmentCmpConroller.js JavaScript Controller File It is used for communicate to server side apex method and fetch the record using init fuction.
fileAttachmentCmpHelper.js JavaScript Helper File It is used for refresh the page after delete the record.
wrapperCustomObjCtrCmp.apxc Apex Class Controller It is used for save the upload images on sObject database.

Custom Object:- NewStudent__c

Custom Object Fields:-

Name,

Email__c

Address__c

Custom Object and their fields Display an upload Image on right side of table in the lightning component if a record has an attachment.

Final Output

display attachment image in 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

 

Step 1:- Create Lightning Component : fileAttachmentCmp.cmp

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

fileAttachmentCmp.cmp [Lightning Component File]

  1.    <aura:component controller="wrapperCustomObjCtrCmp" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:isUrlAddressable" access="global" >
  2.  
  3.     <aura:attribute name="wrapListItems" type="NewStudent__c[]"/>
  4.     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  5.     <aura:attribute name="recSelectId" type="String" default=""/>
  6.  
  7.  
  8.     <aura:attribute name="accept" type="List" default="['.jpg', '.jpeg','.pdf']"/>
  9.     <aura:attribute name="multiple" type="Boolean" default="true"/>
  10.     <aura:attribute name="disabled" type="Boolean" default="false"/>
  11.  
  12.  
  13.     <div class="slds slds-p-horizontal--medium">
  14.         <table class="slds-table slds-table--bordered slds-table--col-bordered" style="border-collapse:collapse;">
  15.             <thead> 
  16.                 <tr>
  17.                     <th>Record Id</th>
  18.                     <th>Student Name</th>
  19.                     <th>Address</th>
  20.                     <th>Email</th>
  21.                      <th>Upload File</th>
  22.                     <th></th>
  23.                 </tr>
  24.             </thead>
  25.             <tbody>
  26.                 <aura:iteration items="{!v.wrapListItems}" var="wrapVar" indexVar="index">
  27.                     <tr id="{!wrapVar.recStudentId}">
  28.                         <td>{!wrapVar.recStudentId}</td>
  29.                         <td>{!wrapVar.studentName}</td>
  30.                         <td>{!wrapVar.studentAddress}</td>
  31.                         <td>{!wrapVar.studentEmail}</td>
  32.                         <td>
  33.                             <lightning:fileUpload
  34.                               multiple="{!v.multiple}" 
  35.                               accept="{!v.accept}"
  36.                               recordId="{!wrapVar.recStudentId}" 
  37.                               onuploadfinished="{!c.uploadFileAction}" disabled="{!v.disabled}"/>
  38.                         </td>
  39.                         <td>
  40.                             <aura:if isTrue="{!wrapVar.checkAttachFile}"> 
  41.                                 <lightning:buttonIcon  tabindex="{!wrapVar.recStudentId}" iconName="utility:upload" name="{!wrapVar.recStudentId}" variant="bare" onclick="{!c.navigateAttachFile}"/>
  42.                             </aura:if>
  43.                         </td>
  44.                     </tr>
  45.                 </aura:iteration>
  46.             </tbody>
  47.         </table>
  48.  
  49. <br/><br/>
  50.    <!--Start RelatedTopics Section-->
  51. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  52.  
  53.             <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>
  54.  
  55.             <br/><br/>
  56.             <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>
  57.             <div style="display:block; overflow:hidden;"> 
  58.                 <div style="width: 50%; float:left; display:inline-block">
  59.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  60.                         <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>
  61.                         <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>
  62.                         <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>
  63.                         <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>
  64.                         <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>
  65.                     </ul>
  66.             </div>
  67.  
  68.             <div style="width: 50%; float:left; display:inline-block">
  69.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  70.                         <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>
  71.                         <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>
  72.                         <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>
  73.                         <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>
  74.                         <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>
  75.                     </ul>
  76.                 </div>
  77.                <div style="clear:both;"></div> 
  78.                <br/>
  79.                 <div class="youtubeIcon">
  80.                     <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>
  81.                 </div>
  82.     </div>
  83.  
  84. </div>
  85.  
  86.   <!--End RelatedTopics Section-->
  87.  
  88.  
  89.     </div>
  90.  
  91. </aura:component>

Step 2:- Create Lightning Component : fileAttachmentCmpConroller.js

 
βœͺ The Big Announcement: -
As per student's demands, I re-opened my eBook of "Salesforce Tutorial" Limited-time huge discount offer Absolutely 50% Off.
I am thinking to give you discount offer occasion of Gandhi Jayanti for a powerful "Salesforce admin course" where you can Understand from Basic Concepts to advanced label in Salesforce.
πŸ‘‰ So Don't MISS it... (Access Right Now)
πŸ‘‰ Get Huge Discount Offer 50%: - Get eBook
 

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

fileAttachmentCmpConroller.js [JavaScript Controller]

  1.    ({
  2. 	doInit : function(component, event, helper) {    
  3.  
  4. 	  var action = component.get("c.appCustomWrapListMthd"); 
  5.  
  6.         action.setCallback(this, function(response){
  7.             var state = response.getState();            
  8.             if(state=='SUCCESS'){
  9.                 var result = response.getReturnValue();            
  10.                 component.set('v.wrapListItems',result);
  11.             }
  12.         });
  13.         $A.enqueueAction(action);        
  14. 	},
  15.  
  16.  
  17.     uploadFileAction : function(component, event, helper) {
  18.         var uploadedFiles = event.getParam("files");
  19.         var documentId = uploadedFiles[0].documentId;
  20.         var fileName = uploadedFiles[0].name;
  21.         var toastEvent = $A.get("e.force:showToast");
  22.         toastEvent.setParams({
  23.             "title": "Success!",   
  24.             "type": "success",
  25.             "message": "File "+fileName+" Uploaded successfully."
  26.         });
  27.         toastEvent.fire();
  28.         $A.get('e.force:refreshView').fire();        
  29.     },
  30.  
  31.  
  32. })

Step 3:- Create Lightning Component : fileAttachmentCmpHelper.js

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

fileAttachmentCmpHelper.js [JavaScript Helper File]

display attachment in lightning component by w3web.net

  1.    ({
  2. 	refreshView : function(component, event, helper) {
  3. 		var action = component.get("c.appCustomWrapListMthd"); 
  4.  
  5.         action.setCallback(this, function(response){
  6.             var state = response.getState();
  7.             //alert(state);
  8.             if(state=='SUCCESS'){
  9.                 var result = response.getReturnValue();
  10.                // alert('result ' + JSON.stringify(result));
  11.                 component.set('v.wrapListItems',result);
  12.             }
  13.         });
  14.         $A.enqueueAction(action);
  15. 	}
  16. })

Step 4:- Create Lightning Application : wrapperCustomObjCtrCmp.apxc

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

wrapperCustomObjCtrCmp.apxc [Apex Class Controller]

  1.    public class wrapperCustomObjCtrCmp {    
  2.  
  3.     public class wrapperCustomClass{
  4.         @AuraEnabled
  5.         public string studentName;
  6.         @AuraEnabled
  7.         public string studentEmail;
  8.         @AuraEnabled
  9.         public string studentAddress;
  10.         @AuraEnabled
  11.         public Id recStudentId;
  12.         @AuraEnabled
  13.         public BOOLEAN checkAttachFile= FALSE;
  14.  
  15.         public wrapperCustomClass(string studentName, string studentEmail, string studentAddress, Id recStudentId,BOOLEAN checkAttachFile){
  16.          this.studentName = studentName;
  17.          this.studentEmail = studentEmail;
  18.          this.studentAddress = studentAddress;  
  19.          this.recStudentId = recStudentId;  
  20.          this.checkAttachFile=checkAttachFile;
  21.         }
  22.     }
  23.  
  24.  
  25.     @AuraEnabled
  26.     public static List<wrapperCustomClass> appCustomWrapListMthd(){
  27.        List<NewStudent__c> newStudent = NEW List<NewStudent__c>();       
  28.        List<wrapperCustomClass> custWrapObj = NEW  List<wrapperCustomClass>();
  29.        List<NewStudent__c> newStudentView =[SELECT Id, Name, Email__c, Address__c FROM NewStudent__c];
  30.  
  31.         Map<Id,contentdocumentlink> projCheckIdDocMap = NEW Map<Id,contentdocumentlink> ();
  32.         Set<Id> projChecklistIdSet= NEW Set<Id> ();
  33.         FOR(NewStudent__c de: newStudentView) {
  34.             projChecklistIdSet.add(de.Id);
  35.         }
  36.         List<Contentdocumentlink> listDocs = [SELECT Id,LinkedEntityId FROM contentdocumentlink WHERE LinkedEntityId IN :projChecklistIdSet
  37.                                               ];
  38.         FOR(Contentdocumentlink doc: listDocs) {
  39.           projCheckIdDocMap.put(doc.LinkedEntityId, doc); 
  40.         }     
  41.  
  42.         BOOLEAN hasAttch= FALSE;
  43.         FOR(NewStudent__c studentObj:newStudentView){
  44.  
  45.             IF(projCheckIdDocMap.get(studentObj.Id)!=NULL){
  46.                 hasAttch=TRUE;
  47.                 system.debug('hasAttch###' + hasAttch);
  48.  
  49.             }ELSE{
  50.                  hasAttch=FALSE;
  51.             }            
  52.          custWrapObj.add(NEW wrapperCustomClass(studentObj.Name,studentObj.Email__c, studentObj.Address__c,studentObj.Id, hasAttch));                       
  53.         }
  54.         RETURN custWrapObj;     
  55.     }
  56.  }

 

 

Further post that would you like to learn in Salesforce

 
 

 

 

FAQ (Frequently Asked Questions)

How do you display an image in the lightning component?

To display images, use the HTML 'img' element. Include an image in your component by uploading it as a static resource or content asset.To display an icon, use the lightning:icon component, which gives you access to Salesforce Lightning Design System icons or your own custom icon.

How do I preview files in lightning component?

A lightning:fileCard component displays a preview of a file. 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.

What is lightning out?

Lightning Out is a technology where one can take Lightning components built on the Force.com platform to the external applications like Sharepoint, SAP, Node apps on Heroku and many others.

 
   
 
 

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