Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrieve image from s3 with nodejs

Please let me know how to retrieve image from s3 with nodejs? Honestly, I could upload an image to s3 with nodejs as follows but the problem is how can I complete to retrieve image from s3?

router.get('/image/:imageId', function (req, res, next) {
    // ????
});

var s3 = new aws.S3({ accessKeyId: config.awsAccessId, secretAccessKey: config.awsAccessKey}); 
var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: config.bucket,
        key: function (req, file, cb) {
            cb(null, file.originalname);
        }
    })
});

router.post('/upload/:id', upload.array('file', 3), function(req, res, next) {
    res.send('Successfully uploaded ' + req.files.length + ' files!');
});
like image 661
PPShein Avatar asked Jan 17 '18 08:01

PPShein


People also ask

How do I get pictures from my S3 bucket to my browser?

To display the contents of an album in the Amazon S3 bucket, the application's viewAlbum function takes an album name and creates the Amazon S3 key for that album. The function then calls the listObjects method of the AWS. S3 service object to obtain a list of all the objects (the photos) in the album.

How do I recover files from S3 bucket?

In the Amazon S3 console, choose your S3 bucket, choose the file that you want to open or download, choose Actions, and then choose Open or Download. If you are downloading an object, specify where you want to save it.

Can S3 store images?

You can create a dataset using images stored in an Amazon S3 bucket. With this option, you can use the folder structure in your Amazon S3 bucket to automatically classify your images. You can store the images in the console bucket or another Amazon S3 bucket in your account.


2 Answers

I've finally found that,

var params = { Bucket: config.bucket, Key: req.params.imageId };
s3.getObject(params, function(err, data) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'});
    res.write(data.Body, 'binary');
    res.end(null, 'binary');
});
like image 186
PPShein Avatar answered Nov 09 '22 05:11

PPShein


You're looking for the getObject() method.

like image 30
Chase Avatar answered Nov 09 '22 05:11

Chase