The Ops Community ⚙️

Bhagya
Bhagya

Posted on

Upload an image to S3 using NodeJs 👷🏻🧡

In this article, Im going to discuss about how to upload an image to AWS S3, the cloud file hosting solution provided by Amazon Web Services.

First install the aws-sdk library.

npm install aws-sdk
Enter fullscreen mode Exit fullscreen mode

Then ,import it to the code, at the top of the file that going to add this file upload to s3 functionality:

import AWS from ’aws-idk’
Enter fullscreen mode Exit fullscreen mode

Now, use the sdk to create an instance of the s3 object. Let’s assign it to a s3 variable.

const s3 = new AWS.S3({
 accessKeyId : process.env.AWS_S3_ACCESS_KEY_ID,
 secretAccessKet: process.env.AWS_S3_SECRET_ACESS_KEY,
})
Enter fullscreen mode Exit fullscreen mode

Here used two environment variables here:

  1. AWS_S3_ACCESS_KEY_ID
  2. AWS_S3_SECRET_ACESS_KEY

Now comes some “administrative works” to do. For that you need to create an IAM profile on AWS (the credentials) with programmatic access with the permissions for AWSCloudFormationFullAccess and AmazonS3FullAccess and an S3 bucket that this user has access to.

Now you need an image blog to upload.

Here you can use the below URL:

const imageURL = ’https://url-to-image.jpg'
const res = await fetch(imageURL)
const blob = await res.buffer()
Enter fullscreen mode Exit fullscreen mode

Or you can get an image sent from a form image field in a multipart form:

const imagePath = req.files[0].path
const blob = fs.readFileSync(imagePath)
Enter fullscreen mode Exit fullscreen mode

Finally, make a call to s3.upload() and call its .promise() method so you can use await to wait until it finishes to get the uploaded files object:

const uploadedImage = await s3.upload({
    Bucket: process.env.AWS_S3_Bucket_NAME,
        Key: req.files[0].originalFilename,
    Body: blod,
 }).promise()
Enter fullscreen mode Exit fullscreen mode

AWS_S3_BUCKET_NAME is the name of the S3 bucket , another environment variable.

Finally , you can get the URL of the uploaded image on S3 by referencing the Location property:

 uploadedImage.Location
Enter fullscreen mode Exit fullscreen mode

You have to make sure that you set the S3 bucket as public so you can access that image URL.

Top comments (0)