Skip to content

Instantly share code, notes, and snippets.

@Arunmainthan
Created December 20, 2019 14:26
Show Gist options
  • Save Arunmainthan/bf8ad85d00fcac2ee70e6fb2d5a34544 to your computer and use it in GitHub Desktop.
Save Arunmainthan/bf8ad85d00fcac2ee70e6fb2d5a34544 to your computer and use it in GitHub Desktop.
Nodejs Express Download file from s3
const express = require('express');
const app = express();
const request = require('request');
app.get('/download-file', function (req, res) {
// sdk way
var s3 = new AWS.S3({});
var options = {
Bucket: 'my-bucket-name',
Key: file,
};
s3.getObject(options, function (err, data) {
res.attachment(file);
res.send(data.Body);
});
// http way
request('https://s3-ap-southeast-2.amazonaws.com/my-bucket-name/mypdf.pdf')
.pipe(res.set('Content-Type', 'application/pdf').set('Content-Disposition', 'inline; filename="mypdf.pdf"'))
})
@AriVagelatos-KSO
Copy link

express and AWS v3 S3:

  public downloadFeedFile = (req: IFeedUrlRequest, res: Response) => {
    const downloadParams: GetObjectCommandInput = parseS3Url(req.s3FileUrl.replace(/\s/g, ''));
    logger.info("requesting S3 file  " + JSON.stringify(downloadParams));
    const run = async () => {
      try {
        const fileStream = await this.s3Client.send(new GetObjectCommand(downloadParams));
        if (fileStream.Body instanceof Readable){
          fileStream.Body.once('error', err => {
            console.error("Error downloading s3 file")
            console.error(err);
          });

          fileStream.Body.pipe(res);

        }
      } catch (err) {
        logger.error("Error", err);
      }
    };

  run();
  
  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment