Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

Yesterday I did a deep night coding session and created a small node.js/JS (well actually CoffeeScript, but CoffeeScript is just JavaScript so let's say JS) app.

what's the goal:

  1. the client sends a canvas datauri (png) to the server (via socket.io)
  2. server uploads image to amazon s3

step 1 is done. 

the server now has a string a la 

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt...

my question is: what are my next steps to "stream"/upload this data to Amazon S3 and create an actual image there? 

Knox https://github.com/LearnBoost/knox seems like an awesome lib to PUT something to S3, but what I'm missing is the glue between the base64-encoded-image-string and actual upload action?

 

Any ideas, pointers and feedback welcome.

1 Answer

0 votes
by (44.4k points)

Using the Javascript aws-sdk:

var AWS = require('aws-sdk');

AWS.config.loadFromPath('./s3_config.json');

var s3Bucket = new AWS.S3( { params: {Bucket: 'myBucket'} } );

inside your router method:- ContentType should be set to the content type of the image file

  buf = new Buffer(req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),'base64')

  var data = {

    Key: req.body.userId, 

    Body: buf,

    ContentEncoding: 'base64',

    ContentType: 'image/jpeg'

  };

  s3Bucket.putObject(data, function(err, data){

      if (err) { 

        console.log(err);

        console.log('Error uploading data: ', data); 

      } else {

        console.log('succesfully uploaded the image!');

      }

  });

s3_config.json file is:-

{

  "accessKeyId":"xxxxxxxxxxxxxxxx",

  "secretAccessKey":"xxxxxxxxxxxxxx",

  "region":"us-east-1"

}

Want to learn more about Amazon Simple Storage Service? You read on AWS S3.

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...