Home Salesforce Download Files From S3 Server using Apex

Download Files From S3 Server using Apex

by Dhanik Lal Sahni

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.

  1. Using S3 API in Apex and Lighting Component
  2. 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.

  1. Get S3 Object Url from Salesforce Custom Object (FileStore)
  2. Connect S3 API using HTTPCallout and use Get Method to retrieve file
  3. Provide complete authentication detail like Bukect, credential etc
  4. After successful authentication, file will be retrieved as blob
  5. 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

You may also like

47 comments

Ranjit February 10, 2020 - 1:38 pm

Thanks for the wounder full Content.

Reply
Dhanik Lal Sahni February 11, 2020 - 12:59 am

Thank You Ranjit.

Reply
Ranjit February 10, 2020 - 1:43 pm

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?

Reply
Dhanik Lal Sahni February 11, 2020 - 12:59 am

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

Reply
Reahul February 18, 2020 - 10:44 pm

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?

Reply
Dhanik Lal Sahni February 21, 2020 - 7:18 pm

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

Reply
Dhanik Lal Sahni February 22, 2020 - 12:52 am

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

Reply
Kevin March 3, 2020 - 9:13 pm

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.

Reply
Dhanik Lal Sahni March 4, 2020 - 12:39 am

Hello Kevin,
You can try using var s3 = new AWS.S3({signatureVersion: 'v4'}); instead of var 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

Reply
Kevin March 4, 2020 - 8:54 pm

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

Reply
Dhanik Lal Sahni March 4, 2020 - 9:03 pm

Thank You Kevin. Good to hear that it is working for you.

Reply
ashish May 2, 2020 - 5:25 pm

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.

Reply
Dhanik Lal Sahni May 3, 2020 - 8:05 am

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

Reply
Koushik July 6, 2020 - 9:01 pm

why do we need ‘closeQuickAction’?

Reply
Dhanik Lal Sahni July 10, 2020 - 10:06 pm

Hello koushik,

In this use case, it is not required. I have removed that. Thank you for pointing out.

Regards,
Dhanik

Reply
Dhanik Lal Sahni July 17, 2020 - 11:59 pm

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

Reply
James July 20, 2020 - 7:56 pm

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!

Reply
Dhanik Lal Sahni September 5, 2020 - 11:11 am

Thank You @James

Reply
Ramesh July 21, 2020 - 10:14 pm

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?

Reply
Dhanik Lal Sahni August 2, 2020 - 11:05 pm

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

Reply
Ramesh July 23, 2020 - 11:28 am

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?

Reply
Dhanik Lal Sahni August 2, 2020 - 11:02 pm

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

Reply
Hailiang July 29, 2020 - 7:57 am

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?

Reply
Dhanik Lal Sahni July 31, 2020 - 9:39 pm

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

Reply
Ramesh August 25, 2020 - 10:30 am

Thank you Dhanik

Reply
vishal Agrawal September 13, 2020 - 9:22 am

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

Reply
Dhanik Lal Sahni September 29, 2020 - 8:51 am

Hello Vishal,

Please check SDK file is correct. Let me know if, you still facing issue. We can connect and resolve.

Thank You,
Dhanik

Reply
Amit September 22, 2020 - 2:24 pm

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.

Reply
Dhanik Lal Sahni September 29, 2020 - 8:47 am

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

Reply
Krunal September 28, 2020 - 10:08 pm

Hi
I am getting 400 bad request error.
Can you please help me with that?

Reply
Dhanik Lal Sahni September 29, 2020 - 8:35 am

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

Reply
Ankur October 7, 2020 - 9:47 am

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”

Reply
Dhanik Lal Sahni October 7, 2020 - 10:36 am

Hello Ankur, Are you getting this issue in all browsers?

Thank You,
Dhanik

Reply
Ankur October 7, 2020 - 2:39 pm

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.

Reply
Rishabh Daga November 12, 2020 - 3:11 pm

Hi Dhanik,

I have created everything mentioned in this blog but didn’t get any response when clicked view files.

Reply
Dhanik Lal Sahni November 17, 2020 - 9:36 am

Hello Rishab,

Let me know when we can connect to resolve your issues.

Thank You,
Dhanik

Reply
Rishabh Daga November 12, 2020 - 3:12 pm

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

Reply
Dhanik Lal Sahni November 17, 2020 - 9:35 am

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

Reply
manasi June 16, 2021 - 10:31 pm

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.

Reply
Dhanik Lal Sahni July 3, 2021 - 1:45 pm

Hello Mansi,

What error you are getting? Can you give issue detail so that i can check code issue.

Thank You,
Dhanik

Reply
Allen August 1, 2021 - 11:20 am

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!

Reply
Dhanik Lal Sahni August 2, 2021 - 7:59 am

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

Reply
Raphael D November 16, 2021 - 8:05 pm

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.

Reply
Dhanik Lal Sahni November 18, 2021 - 10:20 pm

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

Reply
Sunil March 31, 2022 - 1:07 am

@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.

Reply
Dhanik Lal Sahni April 18, 2022 - 11:33 am Reply

Leave a Comment