Uploading a base64 image from IOS to S3 using Node.js

Problem

I have the following code to upload an image from ios device to AWS S3 using node.js:

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

  var s3bucket = new AWS.S3({params: {Bucket: 'forplay-static', Key: 'test.png'}});
  s3bucket.putObject(buf, function(err, data) {
    if (err) {
      return res.send({ success: false, err: err });
    } else {
      return res.send({ success: true });
    }
  });

The image I am posting is: http://pastebin.com/kcmXJbRd

This returns the following error in err:

{ "code": "UnexpectedParameter", "name": "UnexpectedParameter" }

What is the correct way of uploading a base64 image to S3?

Problem courtesy of: Serhat Ozgel

Solution

You can't create a bucket with a key. Keys identify the resources within the buckets. Not sure what AWS client you're using, so I'm not sure EXACTLY what it should look like, but probably something like this:

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

var s3 = new AWS.S3();
s3.putObject({Bucket: 'forplay-static', Key: 'test.png', Body: buf}, function(err, data) {
  if (err) {
    return res.send({ success: false, err: err });
  } else {
    return res.send({ success: true });
  }
});

EDIT: Now that I know aws-sdk, I've changed the code above based on the docs here. I just skipped the createBucket step. You pass the bucket and key parameter to the putObject method, NOT the AWS.S3 constructor.

Solution courtesy of: tandrewnichols

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.