Endpoint for file upload (API gateway + Lambda + Python)

Hi,

I’m pretty new to Serverless so please excuse the stupid question. I have a POST endpoint configured with lambda-proxy and working fine with some test data (path variables and query variables are read correctly and so on).

The next step is actually to use the endpoint to upload a file the way my current Flask app works (i.e. with a standard request such as

curl --form "catalogue=@FILE_NAME.zip" ENDPOINT

).
However I cannot seem to find a way to code the endpoint so that you can upload a zip file and save it locally with lambda. In other words, my function below should retrieved the posted data (the zip file) in the event object and save it to the temp folder for further processing (or store it in s3, it’s really the same).

def index(event, context): # read from event the uploaded file and save it as FILE.zip in the temp folder

Can somebody have a detailed explanation or some pointers on how to achieve this?

Thx

1 Like

Firstly, you need to (via console only currently) in “Binary Support” add “multipart/form-data”.
This is the Content-Type used by POSTs that include files.

Next, in your code you need to parse the request body itself. Python provides a simple function for this : cgi.parse_multipart

from cgi import parse_header, parse_multipart
from io import BytesIO

def post_file(event, context):

    c_type, c_data = parse_header(event['headers']['Content-Type'])
    assert c_type == 'multipart/form-data'
    form_data = parse_multipart(BytesIO(event['body'].decode('base64')), c_data)

However, it loses the filename along the way.

It’s theoretically possible, in theory, to also use the cgi.FieldStorage, but I haven’t tried yet.

4 Likes

How do you get API gateway to give you the body as base64? For me (python3.6) it’s a utf-8 string.

Add multipart/form-data as Binary Media Types in your api’s settings through console or by open api documentation

Please find detail here https://stackoverflow.com/questions/41756190/api-gateway-post-multipart-form-data

I hope it helps