Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to download file from aws s3 bucket in nestjs

Tags:

nestjs

My code is

AWS.config.update({accessKeyId:'my_access_key',secretAccessKey:'my_key'});
consts3 =new AWS.S3();
const option ={ 
 Bucket:'bucket_name',
 key:'key'
 };
 res.setHeader('Content-disposition','attachment; filename=abc.mp3');
 const filestream = createReadStream('hme/comp/documents/abc.mp3);
 filestream.pipe(res);

I want to download file from AWS s3 bucket in nestjs

like image 344
ShrJoshi Avatar asked Oct 27 '25 03:10

ShrJoshi


1 Answers

You can use s3.getObject() function for this purpose.

s3.getObject(
  { Bucket: "my-bucket", Key: "abc.mp3" },
  function (error, data) {
    if (error != null) {
      alert("Failed to retrieve an object: " + error);
    } else {
      alert("Loaded " + data.ContentLength + " bytes");
      // do something with data.Body
    }
  }
);

For streaming the file you can use this.

var options = {
    Bucket    : 'my-bucket',
    Key    : 'key',
};

res.attachment(fileKey);
var fileStream = s3.getObject(options).createReadStream();
fileStream.pipe(res);

Download to specific location with following code:

var file = require('fs').createWriteStream('your/download/path');
s3.getObject(params).createReadStream().pipe(file);
like image 99
vivekpadia70 Avatar answered Oct 29 '25 18:10

vivekpadia70



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!