AllenC
AllenC

Reputation: 2754

Uploading image to s3 using aws sdk

I'm currently using AWS Services to create a user profile.

Basically I can already add user details like (name, gender, interests)

I'm using API Gateway to accept the params I send using PostMan, then it the API gateway POST method will send the request to AWS Lambda then I use aws sdk to insert the data to Dynamodb.

What I would like is to upload an image to the user and the file will be saved to s3, then I'll store the url from s3 to dynamodb together with other user details.

My current lambda code is this:

const AWS =  require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'XXXXXX', apiVersion: 'XXX'});
const uuidv4 = require('uuid/v4');

exports.handler = function(event, context, callback) {
  const params = {
    Item: {
      'uuid': {  S: "i_" + uuidv4() }, 
      'profileImage': { S: event.profileImage },
      'name': { S: event.name }
     }, 
     TableName: 'users'
   };

   dynamodb.putItem(params, function(err, data) {
    const response = {
        status: 200, 
        message: JSON.stringify('A record has been created')
    };
    if (err) {
        console.log(err);
        callback(err);
    } else {
        console.log(data);
        callback(null, response);
    }
  });
};

How can I upload an image programatically using the services I mentioned. The articles I found online is only uploading an image alone and not thru Api Gateway

Upvotes: 2

Views: 224

Answers (1)

AlexK
AlexK

Reputation: 1420

Unfortunately, I am not quite proficient in JS, but I will give you the approach I used in Python to upload an image to S3.

Since you cannot pass an entire object (like image, zip file or w/e) through API gateway, you have to include it in the payload of your POST.

An image can be represented as base64 encoded string that you can save to S3. Using the SDK, once the operation is successful, you will recieve the upload address or you can generate yourself (that is quite simple, a lot of guides on the internet).

As the image in S3 will be just a base64 encoded string by default, you will need to specify the type (Content-Type header) of object you are uploading to S3, so you can open the image afterwards(in a browser for example).

Upvotes: 1

Related Questions