AWS API to upload file in S3 and write record in DB

Viewed 1650

I need to implemnt a AWS backend API that allows the users of my mobile app to upload a file (image) in Amazon S3. Creating an API directly interfaced with the Amazon S3 is not an option because i will not be able to correlate the uploaded file to the record of the user on DynamoDB. I've thought to create a Lambda function (Java) triggered by an API that performs the following steps: 1) calls the Amazon S3 functionality to upload the file 2) write the record into my Dynamo DB with the reference of the file Is there a way to provide a binary file in input to my Lambda function exposed as API?

please let me know. thank you!

davide

1 Answers

The best way to do this is with presigned URLs. You can generate a URL that will let the user upload files directly to S3 with specific name and type. This way you don't have to worry about big files slowing down your server, lambda limits, or double charges for bandwidth. It's also faster for the user in most cases and supports S3 transfer acceleration.

The process can look something like:

  1. User requests link from your server
  2. Your server writes an entry in DynamoDB and returns a presigned URL
  3. User uploads file directly to S3 using presigned URL (with exact name of your server's choice)
  4. Once upload is done you either get a notification using Lambda, or just have the user tell your server the upload is done
  5. Your server performs any required post-processing and marks the file as ready

And to answer your actual question, yes, there is a way to pass binary data to Lambda functions. The link is a step-by-step tutorial, but basically in API Gateway you have to set "Request body passthrough" to "When there are no templates defined (recommended)" and fill in your expected content types. Your mapping should include "base64data": "$input.body", and you need to setup your types under "Binary Support". In your actual lambda function, you should have access to the data as "base64data".

Related