/

How to Upload an Image to S3 Using Node.js

How to Upload an Image to S3 Using Node.js

In this blog post, I am going to explain how to upload an image to AWS S3 using Node.js. AWS S3 is a cloud file hosting solution provided by Amazon Web Services.

If you’re interested in learning how to upload files to S3 from Node.js, check out my previous blog post here.

To get started, you’ll need to install the aws-sdk library:

1
npm install aws-sdk

Once installed, import the library at the top of the file where you’re going to add the file upload to S3 functionality:

1
import AWS from 'aws-sdk'

Next, create an instance of the S3 object using the SDK and assign it to a s3 variable:

1
2
3
4
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_S3_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_S3_SECRET_ACCESS_KEY,
})

Note that we’re using two environment variables, AWS_S3_ACCESS_KEY_ID and AWS_S3_SECRET_ACCESS_KEY.

Now, there are a few administrative tasks you need to complete. You’ll need to create an IAM profile on AWS with programmatic access and the permissions for AWSCloudFormationFullAccess and AmazonS3FullAccess. Additionally, create an S3 bucket that this user has access to. For more details on this, you can refer to the documentation and articles available.

Next, you’ll need an image blob to upload. There are two ways you can obtain the image:

  1. Use a URL:

    1
    2
    3
    const imageURL = 'https://url-to-image.jpg'
    const res = await fetch(imageURL)
    const blob = await res.buffer()
  2. Get the image from a form image field upload in a multipart form:

    1
    2
    const imagePath = req.files[0].path
    const blob = fs.readFileSync(imagePath)

Once you have the image blob, you can make a call to s3.upload() and use its .promise() method to await the completion of the upload and get the uploaded file object:

1
2
3
4
5
const uploadedImage = await s3.upload({
Bucket: process.env.AWS_S3_BUCKET_NAME,
Key: req.files[0].originalFilename,
Body: blob,
}).promise()

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

Finally, to get the URL of the uploaded image on S3, you can reference the Location property of the uploadedImage object:

1
uploadedImage.Location

Remember to set the S3 bucket as public so that you can access the image URL.

Tags: AWS, Node.js, S3, image upload