How to show images stored in Salesforce using Lightning component?

How to show images stored in Salesforce using Lightning component?

Custom Object:




Lightning Component:


  1. <aura:component implements = “force:appHostable”  
  2.                 controller = “PhotoController”>  
  3.       
  4.     <aura:attribute type = “String[]” name = “listURLs”/>      
  5.         
  6.     <aura:handler name = “init” value = “{!this}” action = “{!c.onInit}”/>   
  7.       
  8.     <div class = “slds-box slds-theme_default”>    
  9.           
  10.         <aura:iteration items = “{! v.listURLs }” var = “imgStr”>  
  11.               
  12.             <img src = “{! imgStr }”/><br/><br/>  
  13.               
  14.         </aura:iteration>  
  15.           
  16.     </div>  
  17.       
  18. </aura:component>  



Lightning Component JavaScript Controller:


  1. ({      
  2.         
  3.     onInit : function( component, event, helper ) {      
  4.             
  5.         var action = component.get( “c.fetchPhotos” );      
  6.         action.setCallback(this, function( response ) {        
  7.                   
  8.             var state = response.getState();       
  9.             if ( state === “SUCCESS” )   {      
  10.                       
  11.                 var records = response.getReturnValue();     
  12.                 component.set( “v.listURLs”, records );  
  13.                       
  14.             }      
  15.                   
  16.         });        
  17.         $A.enqueueAction(action);     
  18.             
  19.     }    
  20.         
  21. })   



Apex Class:


  1. public class PhotoController {  
  2.       
  3.     @AuraEnabled    
  4.     public static List < String > fetchPhotos() {  
  5.           
  6.         List < String > listURLs = new List < String >();  
  7.         for ( Photo__c objPhoto : [ SELECT Image__c FROM Photo__c ] ) {  
  8.               
  9.             String imageTag = objPhoto.Image__c.replace( ‘&’‘&’ );  
  10.             listURLs.add( imageTag.substring( imageTag.indexOf( ‘src=’, 0 ) + 5, imageTag.lastIndexOf( ‘alt=’ ) – 2 ) );  
  11.               
  12.         }  
  13.           
  14.         return listURLs;  
  15.           
  16.     }  
  17.   
  18. }  



Output:





Leave a Reply