Download S3 bucket file from Salesforce

Author - Webner
21.06.2021
|
0 Comments
||

When we are working with Salesforce and s3, sometimes we need to download a file from the s3 bucket without using an HTTP request. We can achieve this by generating URLs from apex code. This is a signed URL to access any file of the bucket.
awsKey = ’*******’; // S3 bucket key
awsSecret =’***********’; // s3 bucket secret
bucketName = ‘***********’; // s3 bucket name
region = ‘*********’; // s3 bucket region
filename = EncodingUtil.urlEncode(fileName, 'UTF-8'); // name of file which you want to download
String url; // url which enables you to download file
Date gmtDate = Datetime.now().dateGmt();
Time gmtTime = Datetime.now().timeGmt();
DateTime currentDate = DateTime.newInstance(gmtDate, gmtTime);
string exipredFormat = '1600';
String todayformat = currentDate.format('yyyyMMdd');
String key = 'AWS4' + awsSecret;
Blob DateKey = Crypto.generateMac('hmacSHA256',Blob.valueOf(todayformat),Blob.valueOf(key));
Blob DateRegionKey = Crypto.generateMac('hmacSHA256',Blob.valueOf(region),DateKey);
Blob DateRegionServiceKey = Crypto.generateMac('hmacSHA256',Blob.valueOf('s3'),DateRegionKey);
Blob SigningKey = Crypto.generateMac('hmacSHA256',Blob.valueOf('aws4_request'),DateRegionServiceKey);
String canonical = 'GET\n'+
'/'+fileName+'\n'+
'X-Amz-Algorithm=AWS4-HMAC-SHA256&'+
'X-Amz-Credential='+ awsKey +'%2F'+todayformat+'%2F'+region+'%2Fs3%2Faws4_request&'+
'X-Amz-Date='+todayformat+'T'+currentDate.format('HHmmss')+'Z&'+
'X-Amz-Expires='+exipredFormat+'&X-Amz-SignedHeaders=host\n'+
'host:'+bucketName+'.s3.amazonaws.com\n\n'+
'host\n'+
'UNSIGNED-PAYLOAD';
Blob canonicalsign = Crypto.generateDigest('SHA-256', Blob.valueOf(canonical));
Blob StringToSign = Blob.valueOf('AWS4-HMAC-SHA256\n'+
todayformat+'T'+currentDate.format('HHmmss')+'Z'+'\n'+
todayformat+'/'+region+'/s3/aws4_request\n'+
EncodingUtil.convertToHex(canonicalsign));
Blob bsig = Crypto.generateMac('hmacSHA256',StringToSign,SigningKey);
url = 'https://'+bucketName+'.s3.amazonaws.com/'+fileName+'?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential='+ awsKey +'/'+todayformat+'/'+ region +'/s3/aws4_request&X-Amz-Date='+todayformat+'T'+currentDate.format('HHmmss')+'Z&X-Amz-Expires='+exipredFormat+'&X-Amz-SignedHeaders=host&X-Amz-Signature='+EncodingUtil.convertToHex(bsig);

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *