Skip to content

Instantly share code, notes, and snippets.

@dhaniksahni
Created January 23, 2020 16:30
Show Gist options
  • Save dhaniksahni/72d55124c938c22302b655f1b26e0cbe to your computer and use it in GitHub Desktop.
Save dhaniksahni/72d55124c938c22302b655f1b26e0cbe to your computer and use it in GitHub Desktop.
Download S3 File In Lighting
<aura:component
controller="S3Controller"
implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
access="global">
<aura:attribute name="data" type="String" />
<aura:attribute name="recordId" type="String" />
<aura:attribute name="showFileLink" type="boolean" />
<lightning:button variant="brand" label="View Files" onclick="{!c.getData}" />
<aura:if isTrue="{!v.showFileLink}">
<a href="{!v.data}">Download File</a>
</aura:if>
</aura:component>
({
getData : function(component, event, helper) {
helper.requestFiledata(component, event);
}
})
({
requestFiledata: function(component, event) {
//**dataURL to blob**
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
//**blob to dataURL**
function blobToDataURL(blob, callback) {
var a = new FileReader();
a.onload = function(e) {
callback(e.target.result);
};
a.readAsDataURL(blob);
}
var action = component.get("c.GetS3FileUsingFileId");
action.setParams({
recordId: component.get("v.recordId")
});
action.setCallback(this, function(a) {
var state = a.getState();
if (state == "SUCCESS") {
var res = a.getReturnValue();
component.set('v.showFileLink',true);
var blobData = "data:" + res.ContentType + ";base64," + res.Content;
component.set("v.data", blobData);
}
});
$A.enqueueAction(action);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment