if you are looking for a simple way to upload images to an Amazon S3 bucket using Node.js, Amazon Simple Storage Service (S3) provides a reliable and scalable solution for storing and retrieving images in the cloud. In this article, we will see the process to upload image to s3 bucket using Node.js.
Introduction
In the modern web development era, image uploads are a common requirement for the applications, such as social media platforms, e-commerce websites, and content management systems. Amazon S3 offers a simple and cost-effective cloud storage solution that allows you to securely store and manage images at any scale.
Why choose Amazon S3 for image storage?
When it comes to storing images, S3 offers several advantages:
- Scalability: S3 allows you to store an unlimited number of images and scale your storage as per your need.
- Durability: S3 ensures that your images are highly durable, with 99.999999999% (11 nines) of durability, protecting your data against hardware failures.
- Availability: S3 provides high availability, allowing you to access your images at any time, from anywhere in the world.
- Security: S3 offers multiple security features, such as bucket policies, access control lists (ACLs), and encryption options, to protect your images from unauthorized access.
- Cost-effectiveness: S3 offers a pay-as-you-go pricing model, allowing you to only pay for the storage and data transfer you use.
Implementation – Upload Image to s3 in NodeJs
Before we start the implementation we need to focus on the previous article in which we learned about APIs and JWT Authentication we will continue in that that project.
Installing required packages
npm install multer aws-sdk
Adding keys in Environment File
AWSBucket=YOUR_BUCKET_NAME
AWS_ACCESS_KEY=YOUR_ACCESS_KEY
AWS_ACCESS_SECRET=YOUR_ACCESS_SECRET
AWS_BUCKET_REGION=YOUR_BUCKET_REGION
If you want to know how to configure the S3 bucket you can go through this article.
Creating Files &Folders
Create a new folder in the root directory named ‘Uploads’ and then a new file in the middleware folder named ‘imageUploader.js’ and then paste this code or follow the below screenshot.
import multer from 'multer';
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null,'./Uploads/');
},
filename: (req, file, callback) => {
callback(null,new Date().toDateString().split(" ").join("")+file.originalname);
}
})
const upload = multer({ storage:storage });
export default upload;
This code will save your image in your directory, logic is if case s3 bucket doesn’t work then your image will be saved in your local.
After this create a new file in the Service folder named ‘S3Bucket.js’ and paste this code or follow the below screenshot.
import S3 from 'aws-sdk/clients/s3';
import dotenv from 'dotenv';
import fs from 'fs';
dotenv.config();
const s3 = new S3({
region: process.env.AWS_BUCKET_REGION,
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_ACCESS_SECRET
});
const s3Controller = {
async uploadToS3(img) {
try {
const fileStream = fs.createReadStream(img.path);
const uploadParams = {
Bucket: process.env.AWSBucket,
Body: fileStream,
Key: img.filename
}
const response = await s3.upload(uploadParams).promise();
return response;
}
catch (e) {
console.log(e);
}
},
}
export default s3Controller;
Now,we will modify the UserModel for the user profile image we will add 2 lines of code you can follow the below screenshot.
UserProfile:{
type: String,
default:''
},
After this, we need to create a new function in the controller (UserController) you can paste the below code or follow the screenshot.
import JWTService from '../Services/JWTService';
import s3Bucket from '../Services/S3Bucket';
async uploadUserImage(req, res, next) {
try {
let _id = req.query.id;
if (req.file) {
let response = await s3Bucket.uploadToS3(req.file);
let UserData = await UserModel.findByIdAndUpdate({ _id }, { UserProfile: response.Location },{ new: true })
return res.json({ status: 200, ImageURL: response.Location, data: UserData })
}
}
catch (err) {
console.log(err)
}
}
We have imported modules and created a function in which we update the user profile image.
After this add 1 line of code in UserRoutes.js or follow the screenshot.
import Upload from '../Middlewares/imageUploader'
router.post('/userProfileImage', Upload.single('UserProfile'), UserController.uploadUserImage);
Hit the EndPoint
Now everything is done let’s hit the endpoint
Your endpoint will be “http://localhost:4000/api/userProfileImage”;
Now Open Postman and follow the screenshot
Here we passed the user id in query and image in FormData.
Now Click on Send Button.
Now at last you can see the key UserProfile and our image is uploaded for any help you can comment.
Read More
https://scribblersden.com/quick-sort/
Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs
Thank You