I want to display an image, which is in an attachment in a customized object, in lightning component.
I make a query like that in the server side controller :
@AuraEnabled
public static Attachment getImage(Id parentId){
if(!Schema.sObjectType.sObject__c.isAccessible()){
throw new System.NoAccessException();
return null;
}
return [select Id, Name, ContentType from Attachment
where parentid=:parentId and ContentType in ('image/png', 'image/jpeg', 'image/gif')];
}
Here is the component :
<aura:component controller="Controller" implements="forceCommunity:availableForAllPageTypes,force:appHostable,flexipage:availableForAllPageTypes">
<aura:attribute name="oct" type="sObject__c[]"/>
<aura:attribute name="actId" type="Id"/>
<aura:attribute name="imageSrc" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:iteration var="a" items="{!v.act}">
<div>{!a.Name} : {!a.Description__c}</div>
<img src="{!v.imageSrc}" />
<br/>
</aura:iteration>
and the part of the client side controller :
({
doInit : function(component, event, helper) {
var actionImage = component.get("c.getImage");
actionImage.setParams({
parentId : component.get("v.actId")
});
actionImage.setCallback(this, function(rep){
var attachment = rep.getReturnValue();
component.set("v.imageSrc", "/servlet/servlet.FileDownload?file=" + attachment.Id);
});
$A.enqueueAction(actionImage);
}
})
So I got an error for this line, I guess : component.set("v.imageSrc", "/servlet/servlet.FileDownload?file=" + "attachment.Id");
because of the Id. And if I put a "true" Id I see the image, but I don't see how I can retrieve the good Id dynamically…
Best Answer
You can remove double quotes as attachment is JavaScript variable and the correct syntax is: