Categories
JavaScript Answers

How to upload base64 encoded Image to Amazon S3 via Node.js?

Spread the love

To upload base64 encoded Image to Amazon S3 via Node.js, we call the putObject method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.loadFromPath("./s3_config.json");
const s3Bucket = new AWS.S3({ params: { Bucket: "myBucket" } });
const buf = Buffer.from(
  req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),
  "base64"
);
const data = {
  Key: req.body.userId,
  Body: buf,
  ContentEncoding: "base64",
  ContentType: "image/jpeg",
};
s3Bucket.putObject(data, (err, data) => {
  if (err) {
    console.log(err);
    console.log("Error uploading data: ", data);
  } else {
    console.log("successfully uploaded the image!");
  }
});

to convert the base64 string to a buffer with the Buffer.from method.

We replace the prefix with 'base64' before doing the conversion with replace.

Then we create a data object with Body set to the buf buffer.

Finally, we call putObject to upload the data.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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