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

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