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> 


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])
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.

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

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

var url = 'data:application/pdf;base64,' + result;
    .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.

| improve this answer | |
  • 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 Jun 11 '19 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 Jun 11 '19 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 Jun 12 '19 at 3:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.