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.
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
47 comments
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
[…] https://salesforcecodex.com/2020/01/download-files-from-s3-server-using-apex/ https://salesforcecodex.com/2020/01/uploading-files-to-s3-server-using-apex/ […]
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
Hey Dhanik,
I am using up’s code,upload a pdf file,
then use firefox broswer can download the file,
but grome is cannot ,
can you help me?
Hey Hailiang,
May be chrome setting issue. Ideally, it should work in chrome as well.
Have you tried to debug code? Any issue showing in the console log while opening in chrome.
Thank You,
Dhanik
Thank you Dhanik
Hi DHANIK,
I am not able to use SDK file in lightning component, It is not getting loaded, what am I missing, any setting required for it?
Thank you,
Vishal
Hello Vishal,
Please check SDK file is correct. Let me know if, you still facing issue. We can connect and resolve.
Thank You,
Dhanik
Hey Dhanik,
Great Content,
But How to upload file directly in S3 . using file uploader in lighting component. and file didn’t stored in Salesforce.
Hello Amit,
You can do it. When you upload document, get the blob of that attachment and call Apex code with that blob.
UploadDocuments method which is using recordid as parameter, you can pass blob as well. You can skip all code which is for getting attachment content. You can skip code from line# 81 to 95 of this apex method.
Thank You,
Dhanik
Hi
I am getting 400 bad request error.
Can you please help me with that?
Hello Krunal,
Please check complete error using response.getBody(). This error comes normally with wrong token. Please send meeting link to resolve your issue.
Thank You,
Dhanik
I am able to download only Docx files using this code. While trying to download png/ pdf file, it throws an error in the console – ‘Not allowed to navigate top frame to data URL”
Hello Ankur, Are you getting this issue in all browsers?
Thank You,
Dhanik
Hey Dhanik,
Thanks for replying,
The code is working fine in Firefox but throwing the above error in Chrome. Most of my users are using chrome so need a solution for that.
Hi Dhanik,
I have created everything mentioned in this blog but didn’t get any response when clicked view files.
Hello Rishab,
Let me know when we can connect to resolve your issues.
Thank You,
Dhanik
Hi Dhanik,
I have a use case where i have to GET files from s3 in Salesforce and then push it to BOX (third party app).
Can you help me in this regard.
Thanks in advance
Hello Rishabh,
I will surely help you on this. For immediate response, please call me on mobile or join our telegram link.
Thank You,
Dhanik
I have a use case where i have to GET files from s3 bucket in Salesforce and then download it from salesforce.
tried both the ways from this blog but getting error.
Can you please help me here.
Hello Mansi,
What error you are getting? Can you give issue detail so that i can check code issue.
Thank You,
Dhanik
Hi Dhanik,
Much like Kevin, I’m also getting the signature version 4 error, however I’m using the S3 API in Apex and LC method. I can’t figure out how to set this, I was wondering if you had any ideas?
Thank you for the excellent guides!
Hello Allen, Let me update or write another blog for using signature version 4. You can check our other blog Use Named Credential to Upload File in S3 which is using AWS Signature Version 4.
Thank You,
Dhanik
Thank you so much! very helpful !
Is there a way to secure the call in the LWC solution ? The secret key is exposed in the browser.
Hello Raphael,
You can use named credential for this or you can also store encrypted credentials in custom metadata. You can check this post ( ) for downloading files using named credentials from AWS.
Thank You,
Dhanik
@DHANIK LAL SAHNI
Thanks for the content you posted.
I have one requirement, where, once I download the s3 file as you mentioned, I need to render that content in lightning component or I need to display the file (it could be any type of files). Can you help me on this.
Hello Sunil,
Please check our post https://salesforcecodex.com/salesforce/view-s3-file-in-lightning-web-component/
Thank You,
Dhanik