0

I have a requirement wherein i need to display uploaded files as preview in a lightning component. I have tried it with the below code but was unsuccessfull: Lightning Component:

<aura:component controller="DocPreview" access="global">
<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

 <iframe src="" aura:id="preview" height="500px" width="500px"></iframe> 

</aura:component>

Lightning Helper:

var preview = component.find("preview");
var file = new File([result], "test");
var myURL= URL.createObjectURL(file);
preview.src =  myURL;

Here result is the Blob returned from the below code: Apex Class:

List<Id> cdLst = new List<Id>();
for(ContentDocumentLink cdLnk : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :parentId])
    cdLst.add(cdLnk.ContentDocumentId);
cvLst = [SELECT VersionData FROM ContentVersion WHERE ContentDocumentId IN :(cdLst) LIMIT 25];

Blob cvData = (Blob)cvLst[0].VersionData;
return EncodingUtil.base64Encode(cvData);

Currently in the iframe below is displayed:

enter image description here

Any help would be highly appreciated.

2
  • Why not use lightning:fileCard?
    – Raul
    Commented Jun 11, 2019 at 16:33
  • It does not directly show the preview. It shows a thumbnail on click of which the file is previewed
    – Rohit
    Commented Jun 11, 2019 at 18:11

1 Answer 1

1

Borrowed from this answer, you should be able to do something like the following:

var url = 'data:application/pdf;base64,' + result;
fetch(url)
    .then(res => res.blob())
    .then($A.getCallback(blob => component.find("preview").src = URL.createObjectURL(new File([blob], 'preview.pdf', { type: 'application/pdf' }))));

Your main problem is that the content you're getting back from the Apex code is bae64 encoded. We need to reverse this encoding to get the binary data back out. Traditionally, we would have used atob, but that method shouldn't be used. Instead, we can use fetch to decode the base64 data back in to a blob, and from there create the File, and finally the Object URL.

3
  • Now there is nothing being displayed in the iframe. Added my component code as well. Let me know if i am doing anything wrong.
    – Rohit
    Commented Jun 11, 2019 at 18:06
  • @Rohit Any error messages on the Developer Console (F12)? Can you verify you're getting the expected data back? We're still missing some information that might be useful. Have you tried building a sscce?
    – sfdcfox
    Commented Jun 11, 2019 at 18:21
  • There's no error on console. Also, i've checked the result and i am getting the base64 string in my controller.
    – Rohit
    Commented Jun 12, 2019 at 3:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .