Skip to main content
image-upload-amazon-s3-nodejs

Amazon S3 Image Upload using Nodejs

This Nodejs tutorial help to upload the image to AWS S3 server using aws-sdk library. Amazon S3 provides virtually limitless storage on the internet.

You can manage buckets, objects, and folders in Amazon S3 by using the AWS Management Console, a browser-based graphical user interface for interacting with AWS services.

Amazon Simple Storage Service (Amazon S3) is a popular cloud platform to store data using services. I will use s3 to upload images into the bucket. It’s very highly scalable, durable, and secure storage.

I will provide a simple script into this node js tutorial to upload image to aws s3 using .upload() method. So the file structure for this example is the following.

app.js : This is the main entry file.
package.json : This file will have all dependency modules information.

Checkout Other NodeJS tutorials,

Step 1: Create an Amazon S3 Account
We need to create an Amazon S3 account and get aws s3 bucket name and access keys to use for uploading images.

Step 2: Install AWS SDK
You can install aws sdk using 'npm i aws-sdk' or added entry "aws-sdk": "^2.175.0" into package.json file and run 'npm update' command.

Step 3: Configure AWS S3
We have Amazon S3 account details, We will define Amazon S3 account details in app.js using access key and secret key.

const AWS = require('aws-sdk')
AWS.config.update({ accessKeyId: process.env.ACCESS_KEY_ID, secretAccessKey: process.env.SECRET_ACCESS_KEY });

I have stored application secrets as an env variable in the server, You can use the direct secret key and access key.

Step 4: Upload Image using S3:

We are planning to store data in base64 string into AWS server, so we will convert image data into base64 in nodejs app and send it to amazon S3 server. We will do the following steps to upload files using aws s3 sdk.

Create an S3 instance using aws-sdk class.
const s3 = new AWS.S3();

We will convert image data into base64 string using the method.

const base64Data = new Buffer(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64')

We will get image type ie: jpeg, png or gif

const type = base64.split(';')[0].split('/')[1]

We will create the final upload image params,

const params = {
  Bucket: process.env.S3_BUCKET,
  Key: `avatar`,
  Body: base64Data,
  ACL: 'public-read',
  ContentEncoding: 'base64', // required
  ContentType: `image/${type}`
}

Now send a request to S3 server to upload image with params.

s3.upload(params, (err, data) => {
  if (err) { return console.log(err) }
  
  // Continue if no error
  // Save data.Location in your database
  console.log('Image successfully uploaded.');
});

We have used upload() method but you can also use another method which is putObject().

Leave a Reply

Your email address will not be published. Required fields are marked *