How to upload image/file to AWS S3 bucket using nodejs
In this era amazon provides the best web services. So today i am going to explain how we can store data on AWS S3 bucket with help of nodejs. firstly after sign in on amazon website you need to follow these steps for upload data into S3 bucket.
1. Go to AWS console https://console.aws.amazon.com/s3/
2. Choose Create bucket.
3. Enter bucket name.
4. Select Region what you want to choose
5. Then bucket to make public.
6. Click on save
7. Now bucket created
Setup project for node js:
1 . mkdir node
2 . cd /node
3 . Run these commands for install node project
1 2 |
npm install npm install express –save |
4. Now create index.js file in the root of the project folder. And paste this code.
1 2 3 4 5 6 7 8 9 10 |
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); }); |
5. Install ‘aws-sdk’ library for use AWS S3 bucket
1 |
npm install aws-sdk |
6. After that add this code on top of page
1 2 |
const fs = require('fs'); const AWS = require('aws-sdk'); |
7. This is AWS bucket details what you need to set in nodejs code.
1 2 3 4 5 6 7 8 9 10 |
const ID = 'XXXXXXX'; const SECRET = 'XXXXXXXXX'; // The name of the bucket that you have created const BUCKET_NAME = 'BUCKET_NAME'; const s3 = new AWS.S3({ accessKeyId: ID, secretAccessKey: SECRET }); |
This function i have created for upload file on aws s3 bucket. I use fs library for read file content and send file to the bucket with this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
function uploadS3(filepath, filename, uploadpath) { console.log(filepath) fs.readFile(filepath, function (err, data) { if (err) throw err; // Something went wrong! // Read content from the file const fileContent = fs.readFileSync(filepath); // Setting up S3 upload parameters const params = { Bucket: BUCKET_NAME, Key: uploadpath+'/'+filename, // File name you want to save as in S3 Body: fileContent, ACL:'public-read' // Make file public }; // Uploading files to the bucket s3.upload(params, function(err, data) { if (err) { throw err; } console.log(`File uploaded successfully. ${data.Location}`); // This code for delete file after upload fs.unlink(filepath, function (err) { if (err) { console.error(err); } console.log('Temp File Delete'); }); console.log({'msg': 'File uploaded successfully!!', 'status': 1}); }); }); }; |
Call function in index.js file
1 |
uploadS3('image.png', 'uploadfile.png', '/uploadpath/'); |
Now run application with this command
1 |
node index.js |
This is tutorial for upload file from node application to AWS S3 bucket if you like this tutorial please share and keep learning for better life. Thanks, 🙂