I have a problem statement wherein I wish to download the file in using Express and NodeJS Framework.
Can I download the file from amazon/s3 bucket without having a login account in AWS ?
I have a problem statement wherein I wish to download the file in using Express and NodeJS Framework.
Can I download the file from amazon/s3 bucket without having a login account in AWS ?
There are three common ways of accessing S3 objects/files without the need for AWS credentials:
Granting public access to the bucket, a folder in the bucket or individual objects. This is probably the easiest to setup and use, but your objects are, well, public.
Use S3 pre-signed url url. These are temporary urls that your backend would have to generate for the front-end to use. The urls can be for downloading or uploading files. Anyone with these urls can download/upload files to your bucket, but since urls are temporary, hot-linking the urls is limited.
Front your bucket with CloudFront. This allows to keep your bucket fully private, and all your files will be accessed through CloudFront edge locations, which can also speedup your website.
I managed to resolve the issue.
var S3 = require('aws-sdk/clients/s3');
var fs = require('fs');
const stream = require('stream');
const request = require('request');
const AWS = require('aws-sdk')
const awsS3 = new AWS.S3()
var app = express();
app.use(cors());
var AWS_ACCESS_KEY_ID = 'AKIA....';
var AWS_SECRET_ACCESS_KEY = 'uQ/l....';
var S3_BUCKET_NAME = 'realindia';
var toUploadFileName = 'abcd.pdf'
app.get('/downloadURL', (req,res,next) => {
const s3 = new S3({
apiVersion: '2021-04-10',
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
signatureVersion: 'v4',
region: 'us-east-2' // region of my bucket and what it says is expected
});
var s3params = {'Bucket': S3_BUCKET_NAME, 'Key': fileName }
s3.getSignedUrl('getObject', s3params, function(err, url) {
if (err) res.json(err);
//To download the File.
var options = {
Bucket : s3params.Bucket,
Key : s3params.Key
};
res.attachment(s3params.Key);
var fileStream = s3.getObject(options).createReadStream();
fileStream.pipe(res);
});
});