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.