Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    • Salesforce Spring ’25 Release: Top Flow Enhancements You Need to Know
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 8
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Download Files From S3 Server using Apex

    Download Files From S3 Server using Apex

    Dhanik Lal SahniBy Dhanik Lal SahniJanuary 24, 2020Updated:February 21, 202047 Comments3 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Download Files From S3 Server using Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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

    apex AWS lightning S3 Server
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleTop 20 Salesforce Developer Interview Questions
    Next Article Audio to Text by Google Speech API in Salesforce Lightning
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Basic Queueable Chaining in Salesforce Apex

    March 31, 2025
    View 47 Comments

    47 Comments

    1. Ranjit on February 10, 2020 1:38 pm

      Thanks for the wounder full Content.

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

        Thank You Ranjit.

        Reply
    2. Ranjit on 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 on 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
    3. Reahul on 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 on 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 on 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
    4. Kevin on 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 on 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 on 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 on March 4, 2020 9:03 pm

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

            Reply
    5. ashish on 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 on 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
    6. Koushik on July 6, 2020 9:01 pm

      why do we need ‘closeQuickAction’?

      Reply
      • Dhanik Lal Sahni on 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
    7. Pingback: View S3 File in Lightning Web Component | SalesforceCodex

    8. Dhanik Lal Sahni on 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
    9. James on 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 on September 5, 2020 11:11 am

        Thank You @James

        Reply
    10. Ramesh on 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 on 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
    11. Ramesh on 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 on 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
    12. Hailiang on 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 on 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
    13. Ramesh on August 25, 2020 10:30 am

      Thank you Dhanik

      Reply
    14. vishal Agrawal on 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 on 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
    15. Amit on 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 on 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
    16. Krunal on 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 on 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
    17. Ankur on 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 on October 7, 2020 10:36 am

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

        Thank You,
        Dhanik

        Reply
        • Ankur on 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
    18. Rishabh Daga on 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 on November 17, 2020 9:36 am

        Hello Rishab,

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

        Thank You,
        Dhanik

        Reply
    19. Rishabh Daga on 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 on 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
    20. manasi on 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 on 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
    21. Allen on 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 on 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
    22. Raphael D on 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 on 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
    23. Sunil on 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 on April 18, 2022 11:33 am

        Hello Sunil,

        Please check our post https://salesforcecodex.com/salesforce/view-s3-file-in-lightning-web-component/

        Thank You,
        Dhanik

        Reply
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.