How to Download Files from S3 Server using Apex and Lightning Component
Downloading or reading files from S3 server is required most of time in our Salesforce projects. This post will explain how we can download files from AWS S3 Server and show using Lightning component.
We can download files using two ways.
- Using S3 API in Apex and Lighting Component
- Using AWS Java Script SDK in Lightning Component
1. Using S3 API in Apex and Lighting Component
To download file using Apex, we have to use HTTP Callout with uploaded file URL. As in our last post How to Upload Files to S3 Server using Apex , we have uploaded file in S3 server and stored S3 file information like file’s S3 url in custom object File Store.
GetObject method of S3 Server API will be used to get file. Below are important information about GetObject
- To download file, we must have access to S3 object.
- This will return latest version of file.
Apex Code:
Let us download uploaded file using Apex and show that file using lightning.
- Get S3 Object Url from Salesforce Custom Object (FileStore)
- Connect S3 API using HTTPCallout and use Get Method to retrieve file
- Provide complete authentication detail like Bukect, credential etc
- After successful authentication, file will be retrieved as blob
- Encode this blob to show in lightning
BaseException class is custom exception class to identify error detail.
Call above service class in controller class. Controller class will be called from Lightning component.
Lightning Component:
2. Using Java Script SDK in Lightning Component
In this approach file will be downloaded using AWS Javascript SDK. We have to download that SDK library and add that into static resource.
This library will be loaded in lightning component to do operation related to file upload/download files.
<ltng:require scripts="/resource/AWSSDK" afterScriptsLoaded="{!c.doInit}"/>
Apex Code :
This apex class will be retrieve file url to which we need to download.
Complete Code:
Lightning Component Code:
SDK’s GetObject function will be used to get file. We have to pass complete AWS credential to get handshake with AWS.
AWS.config.update({ accessKeyId: "***************", // Set Access Key secretAccessKey: "****************", // Set Secret Key region_config: "eu-west-1" // Set your bucket region });
Below code will create object of S3 libray class. getSignedUrl method of object will get pre signed url of file.
var s3 = new AWS.S3(); s3.getSignedUrl('getObject', {Bucket: strBucket, Key: strKey}, function (err, url) { });
After file url is retrieved, it is downloaded using XMLHttpRequest.
Lightning Component Code:
Reference:
https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html
View Comments (46)
Thanks for the wounder full Content.
Thank You Ranjit.
When I am Using S3 API in Apex. I have used same code in this page, but I am getting error as below
Invalid type: FileData
Invalid type: BaseException
Invalid type: FileStore__c
Variable does not exist: file
Do I need to install any package?
Hello Ranjit,
BaseException is custom exception class and FileData is wrapper class. FileStore__c is custom object to store file detail. if you have similar use case then create this object otherwise comment this section.
I have updated code base with above files.
Thank You,
Dhanik
When trying to upload AWSSDK to static resource I am getting Error: This file exceeds the maximum size limit of 10MB.
Error Error: Required fields are missing: [MIME Type]. Is there any recommendation to resolve this?
Hello Reahul,
Static resource is about 1.7MB so it will not give error while uploading. You can try downloading AWS.S3 js file at https://sdk.amazonaws.com/builder/js/
Thank You,
Dhanik
Hello,
You can download file from https://raw.githubusercontent.com/aws/aws-sdk-js/master/dist/aws-sdk.min.js. This file need to be uploaded in static resource.
Thank You,
Dhanik
Hi DHANIK,
I used Java Script SDK in Lightning Component, and I hardcode the url which should be saved in object, but I am getting error message of 'The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.'
Do you know why is this happening?
Thanks.
Hello Kevin,
You can try using
var s3 = new AWS.S3({signatureVersion: 'v4'});
instead ofvar s3 = new AWS.S3();
in DownloadS3FileController.js.You can refer link https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html or https://stackoverflow.com/questions/26533245/the-authorization-mechanism-you-have-provided-is-not-supported-please-use-aws4 for help.
Thank You,
Dhanik
Hi DHANIK LAL SAHNI,
Thank you for your replying, the problem has been solved with your advice and one more thing differentiate with S3 method is to update config as flow
AWS.config.update({
accessKeyId: component.get('v.key'), // Add Access Key
secretAccessKey: component.get('v.secretKey'), // Add Secret Key
region: "ca-central-1"
});
Thank you again, really appreciate your help.
Regards,
Kevin
Thank You Kevin. Good to hear that it is working for you.
Hi Dhanik,
Using S3 API in Apex and Lighting Component
i create all component and apex class as u write in this blog but when i click on view button no error no response nothing happened,please help me to find the issue.
Sure Ashish. Have you tried to debug the issue? Please debug it and if you need help, please send mail to contactus@saleforcecodex.com or saleforcecodex@gmail.com for connecting.
Thank You,
Dhanik
why do we need 'closeQuickAction'?
Hello koushik,
In this use case, it is not required. I have removed that. Thank you for pointing out.
Regards,
Dhanik
Hey Akshay,
This error normally raised due to wrong token. Let us connect on this.
I have tried sending email to you but that got bounced.
Thank You,
Dhanik
Thanks for the tips. I was working on a similar functionality, but was getting an error saying File could not be opened, due to "byte shaving". However, after using your approach, I was able to get a PDF API call working. Much appreciated!
Thank You @James
Hi
I am trying to download files from S3 bucket using Apex, i am able achieve this using code available above but this works only when we know the file name, so can you guide me how to download the files without using file name?
Hello Ramesh,
We should download files based on some filters. If we try to download all files, it will be a performance problem. You can refer post-https://salesforce.stackexchange.com/questions/146657/cannot-list-objects-using-aws-s3 to get all S3 bucket files.
Thank You,
Dhanik
Hi DHANIK,
I need to list down the file names within s3 bucket on Salesforce visualforce page, is it possible using apex code to fetch the file names present in my s3 bucket?
Hello Ramesh,
It is possible. You can use apex to get all files present in S3 server. Refer post https://salesforce.stackexchange.com/questions/146657/cannot-list-objects-using-aws-s3 for this.
Thank You,
Dhanik