1. Create an api get request to node application. eg: Get '/api/get-file/:id'
2. Install packages aws-sdk , or express npm i express aws-sdk , leave it if pre- installed.
3. Follow the below code snippet
Aws S3 service provide getObject and createReadStream method. Pass the Params to s3.getObject then use createReadStream.
use pipe method in createReadStream and pass the response (res) object to pipe method so it will pipe your stream to response.
You can also use file write Stream location to save Stream in file.
var app = require('express')();var aws = require('aws-sdk');aws.config.update({ region: 'us-east-1' });var s3 = new aws.S3({apiVersion: '2006-03-01'});const BUCKET = '<your bucket name>';app.get('/api/get-file/:id', (req, res) => {let id = req.params.id;var params = {Bucket: BUCKET,Key: id ,};s3.getObject(params).createReadStream().pipe(res);//or// streamObject(id,res);});//The above is simple example you can extend this logs error and check other responsefunction streamObject(key, location) {var params = {Bucket: BUCKET,Key: key,};let stream= s3.getObject(params).createReadStream();stream.on('error', function (err) {console.error(err);});stream.pipe(location).on('error', function (err) {console.error('File Stream:', err);}).on('close', function () {console.log('Done.');});}
Comments
Post a Comment