[SalesForce] Display an image stored in ContentDocument (in lightning experience)

I'd like to display on a lightning component an image, that is stored in the ContentDocument object in lightning experience.

Before I used the Attachment in salesforce classic, with something like that : <img src="{!'/servlet/servlet.FileDownload?file=' + a.image.Id}" alt=""/>, but I need to use it in lighning experience.

I try to use this post but I don't really understand how it works and I can't retrieve the image.

Best Answer

Looking at the Data Model of the Content Object as mentioned in this post, it looks like you need to get Id of the ContentVersion which is tied to you the ContentDocument record. Also to display Contents, the relative url path should be in below format :

/sfc/servlet.shepherd/version/download/contentversionid

Sample code

myApp.app:

<aura:application extends="force:slds" controller="TestCtrl">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
    <aura:attribute name="contents" type="List" default="[]"/>
    <aura:attribute name="prefixURL" type="String" default="/sfc/servlet.shepherd/version/download/"/>
    <aura:iteration items="{!v.contents}" var="content">
        <img src="{!v.prefixURL + content.Id}" width="100" height="100"/>
    </aura:iteration>
</aura:application>

controller.js

({
    doInit : function(cmp){
       var action = cmp.get("c.getContents");
       action.setCallback(this, function(response) {
           var state = response.getState();
           if(cmp.isValid() && state === 'SUCCESS') {
               cmp.set("v.contents", response.getReturnValue()); 
           }
       });
        $A.enqueueAction(action);
    },

})

Apex Class:

public class TestCtrl {

    @AuraEnabled
    public static List<ContentVersion> getContents() {
        Set<Id> contentIds = new Set<Id>();

        for (ContentDocument cont :[Select Id ,Title from ContentDocument]) {
            contentIds.add(cont.Id);
        }

        return [SELECT Id,Title FROM ContentVersion WHERE ContentDocumentId IN :contentIds];
    }
}