0

I am trying to build an API with API gateway to accept a file upload. I am going through lambda so that I can manipulate the file name before passing it on to S3 bucket

In the event body i can see the file contents but can't seem to access the file name.

Right now Im not implementing anything to move file to S3 because I haven't been able to access the file name.

the code is as follows

import sys
import os
import boto3
import json

def lambda_handler(event,context):
eventBody = json.dumps(event['body'])

return {
'statusCode': 200,
'headers': {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
},
'body': eventBody,
'isBase64Encoded': False
}

the event body looks as follows

"----------------------------210938299122441198584130\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n\r\nthis is a test file\r\n----------------------------210938299122441198584130--\r\n"

I can see that the filename is there but I cant seem to access it.

i had been trying

filename = json.loads(eventBody)['filename']

but this does not work. is there a way to access the filename from the post request in lambda?

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
Andrew
  • 13
  • 3
  • FYI your back-end can dictate the key of the uploaded S3 object by creating a pre-signed upload URL and sending that to the client which then uploads directly to that URL without the limitations of proxying the upload request through your Lambda function. – jarmod May 31 '23 at 17:55
  • This may be helpful: [Parse multipart/form-data from body as string on AWS Lambda](https://stackoverflow.com/questions/38599028/parse-multipart-form-data-from-body-as-string-on-aws-lambda) – jarmod May 31 '23 at 18:26
  • Using this video i found it very helpful and this implementation worked, for some reason with some other implementations i was trying there were issues. https://www.youtube.com/watch?v=hROwNOKQTyM – Andrew Jul 11 '23 at 20:55

1 Answers1

0

API Gateway does not handle binary files well (at least from my experience). Assume you have this use case.

A Client app (ie - React) lets a user select and upload a photo that is placed into an S3 bucket. The client can make a request that goes through API Gateway. However- do not try to post the file to API Gateway.

The solution is from an API Gateway endpoint, invoke an S3 operation that generates a presigned URL and then returns that Presigned URL to the client app. Then the Client app uses the Presigned URL (which has a time limit) to upload the photo to the bucket. This is all explained in the link below that is located in the AWS Code Library.

Overview illustration:

enter image description here

Full Code Example:

Create a photo asset management application that lets users manage photos using labels

smac2020
  • 9,637
  • 4
  • 24
  • 38