Home SalesforceApex Use Named Credential to Upload File in S3

Use Named Credential to Upload File in S3

by Dhanik Lal Sahni

We mostly have requirements to upload files in file storage servers like AWS S3 Server, Dropbox, Google Drive, etc. This post will help in uploading files to S3 Server. We will use named credential to upload file in S3 server.

Steps for uploading file in S3 Server using named credential

  1. Create a named credential for AWS Credential
  2. Create an apex class to upload file
  3. Test functionality

1. Create a named credential for AWS Credential

Create a named credential with Authentication Protocol as AWS Signature Version 4.

AWS Signature Version 4 (SigV4) is the process to add authentication information to AWS API requests sent by HTTP.  No need to set any header in this case. All information is shared using this named credential itself.

Named Credential Detail

NameS3Upload
Urlhttps://s3.amazonaws.com/salesforcecodex
or
https://{bucket}.s3.{region}.amazonaws.com
Identity TypeNamed Principle
Authentication ProtocolAWS Signature Version 4
AWS Access Key Id{Your access key}
AWS Secret Access Key{Your secret access key}
AWS Region{your s3 bucket region}
AWS Services3

2 Create an apex class to upload file

Let us create an apex class that will upload files to the AWS S3 server. For this post, I have created one function which will take LinkedEntityId which is a record where the file is attached.

We need blob data of attachment to store in S3 Server. So we have used file content VersionData which is in blob format.

Apart from callout, we need not be required to put any header information for API requests. Named credential will take care of auth headers.

3. Test functionality

Let us test uploading of files. For testing, the below code can be executed in the developer console’s anonymous window to upload a document that is attached to the record id. This recordid can be of case, account, contact or any custom object.

AWSFileService service=new AWSFileService();
service.UploadDocuments('5002v00002qbQxWAAU');

The above code can also be written in one method to make requests dynamic and used by many processes.

@AuraEnabled
public static void UploadDocToS3Server(string recordId)
{
AWSFileService service=new AWSFileService();
service.UploadDocuments(recordId);
}

We can call method UploadDocToS3Server from lightning components.

References:

Signature Version 4 signing process

Checkout previous posts for similar requirements.

Uploading Files to S3 Server using Apex

Download Files From S3 Server using Apex

View S3 File in Lightning Web Component

You may also like

15 comments

N August 3, 2021 - 8:06 pm

Hi Dhanik,

Got here from the previous post about uploading to S3. I’ve tried setting this up but I’m getting an error message :

SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided. Check your key and signing method.XXXXXXAWS4-HMAC-SHA256

The URL I set was:
https://MYBUCKETNAME.s3.eu-west-2.amazonaws.com – is this correct?
Also – I don’t see anywhere where we use trhe filename string and ass it on – am I missing something here?

Thanks,
N

Reply
Dhanik Lal Sahni August 4, 2021 - 8:04 am

Hello N,
You have to use like this https://s3.amazonaws.com/salesforcecodex. Here salesforcecodex is bucket name, so put your bucket name in place of it. I feel it will work if you give proper detail to named credential.

Let us connect, if you face issue even after that. Connect to my linked-in profile for this.

Thank You,
Dhanik

Reply
Download S3 File using AWS Signature Version 4.0 August 5, 2021 - 7:21 pm

[…] to download S3 files, we have to use AWS Signature Version 4 now onwards. We have another post (Use Named Credential to Upload File in S3) which will help in uploading files using AWS Signature Version 4. In this post will go for […]

Reply
Bharat September 11, 2021 - 11:06 pm

Hi Dhanik,

Thanks for your post. It was really helpful. I tried the same for an opportunity record but getting the below error not sure why.
System.HttpResponse[Status=Bad Request, StatusCode=400]”|

Reply
Dhanik Lal Sahni September 13, 2021 - 7:05 pm

Hello Bharat,

Have you checked complete error detail using response.getBody()? This error mostly comes when our URL is not created properly. If all good from your side and still issue, please connect on linked-in or telegram. We will connect and resolve it.

Thank You,
Dhanik

Reply
Wojtek December 3, 2021 - 8:17 pm

Hi,
I’m receiving an Error: 400 The authorization header is malformed; the region ‘eu-central-1’ is wrong; expecting ‘us-east-1

My configuration for named Credentials:
URL: https://s3.amazonaws.com/mybucketname
AWS Region: eu-central-1
AWS Service: S3
I’m wondering what’s wrong

Reply
Dhanik Lal Sahni December 7, 2021 - 1:10 pm

Hey,
Please check this post

Thank You,
Dhanik

Reply
Cuttly Url Shortener in Salesforce | SalesforceCodex February 17, 2022 - 8:05 am

[…] Use Named Credential to Upload File in S3 […]

Reply
Geecel March 24, 2022 - 2:21 pm

Hi I got this error, The XML you provided was not well-formed or did not validate against our published schema salesforce when testing the code above.

Reply
Dhanik Lal Sahni March 25, 2022 - 8:58 pm

Hey Geecel,

Can you check the line where you are getting errors? Let me know, so that we can connect and resolve your issue.

Thank You,
Dhanik

Reply
Geecel March 28, 2022 - 1:34 pm

I was able to resolved the issue. I updated from req.setEndpoint(‘callout:AWSSignature’); to req.setEndpoint(‘callout:AWSSignature’ +’/’+attach.Title.replaceAll(‘[^a-zA-Z0-9\\s+]’,’-‘).toLowerCase()+ ‘.’+attach.FileExtension.toLowerCase()); I hope this helps.
Thankyou!

Reply
Muthukumar June 2, 2023 - 7:50 am

This solution worked out for me, when I was facing Access denied issue, thanks.

Reply
Difference between SOAP and REST API? - SalesforceCodex September 4, 2022 - 11:30 pm

[…] Upload File in S3 using Named Credential OCR App using Salesforce Einstein OCR API Integrate Salesforce with WhatsApp using Twilio API rest and soap apirest api vs soap apirest vs soapsalesforcesalesforce developer interview questionsalesforce developer questionsalesforce interview questionsalesforce questionsfdc interview questionsoap and rest apisoap api vs rest apisoap vs rest 0 comment 0 FacebookTwitterPinterestEmail […]

Reply
Muthukumar June 1, 2023 - 5:27 pm

I am getting ‘403’ Access denied Error. I am using the same code but still getting this error.

Reply
Dhanik Lal Sahni June 12, 2023 - 11:32 am

Hello Muthu,

Please check access to user which you are using to explore API.

Thank You,
Dhanik

Reply

Leave a Comment