Hello guys,
In this blog, we will discuss how to upload an image to Amazon s3 bucket. Amazon s3 provide online storage service. In the Amazon s3 data stored in the bucket. A bucket is just like a folder which contains your data for this we have to create an Amazon web services account ( on https://aws.amazon.com/s3/ )and get an access key Id, secret access key.
Now we have to install Amazon SDK node module.
1 |
$ npm install aws-sdk |
And create a JSON file (aws_config.json) in your project directory that AWS access key id, secret key id, and region.
1 2 3 4 5 |
{ "accessKeyId": "******", "secretAccessKey": "*****", "region": "us-east-1" } |
Now require aws-sdk module and load aws_config.json file.
1 2 |
var aws_module = require('aws-sdk'); aws_module.config.loadFromPath('aws_config.json'); //path of aws_config file. |
create an instance s3 and create a bucket in s3 which contain an image of your project.
1 2 3 4 |
let s3_instance = new aws_module.S3(); let bucketParam = {Bucket: 'jellyfishBucket'}; s3_instance.createBucket(bucketParam); var s3Bucket = new aws_module.S3( { params: {Bucket: 'jellyfishBucket'} } ); |
upload image to s3 bucket :
In ASW s3 bucket image stored with a key. To manage permission and access of AWS s3 bucket with the help of ACL(Access control list).ACL grant permission to the bucket.AWS provides predefined grantees and permission which is called Canned ACL.
ACL:public-read means the owner has full access and other users only read access.
To upload an image in the bucket with a key and body argument takes an image in the byte stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
uploadImage:function(req,res) { let data = { Bucket:'jellyfishBucket', Key: 'image1', Body:req.file('image_name')._files[0].stream._readableState.buffer[0], ACL: 'public-read', ContentEncoding: 'base64', ContentType: 'image/png' }; s3Bucket.upload(data, function (err, data) { if (err) { console.log('Error uploading Image!'); res.json({error: err}) } else { console.log('Image upload successfully!', data); res.json({message: 'Image upload successfully!'}) } } ) }); } |
get an image from the s3 bucket:
To get URL of upload image the getSingedUrl method return signed URL of an object which is expired after a limited time.
1 2 3 4 5 6 7 |
getImage:function(req,res){ let image = {Bucket: 'jellyfishBucket', Key: 'req.body.image_key'}; s3Bucket.getSignedUrl('getObject',image, function(err, url){ console.log('Image url is', url); res.json('Image url:',url); }) } |
Recent Comments