Skip to content

Instantly share code, notes, and snippets.

@tomfa
Last active December 26, 2022 13:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tomfa/87947d2773b60fc3797491d6ef5e3d0e to your computer and use it in GitHub Desktop.
Save tomfa/87947d2773b60fc3797491d6ef5e3d0e to your computer and use it in GitHub Desktop.
Python: AWS lambda receiving form file (with serverless.yml)
# This file is your Lambda function
import base64
import json
import boto3
def save_to_bucket(event, context):
AWS_BUCKET_NAME = 'my-bucket-name'
s3 = boto3.resource('s3')
bucket = s3.Bucket(AWS_BUCKET_NAME)
path = 'my-path-name.txt'
post_data = base64.b64decode(event['body-json'])
headers, data = post_data.decode('utf-8').split('\r\n', 1)
bucket.put_object(
ACL='public-read',
ContentType='text/plain',
Key=path,
Body=data,
)
body = {
"uploaded": "true",
"bucket": AWS_BUCKET_NAME,
"path": path,
}
return {
"statusCode": 200,
"body": json.dumps(body)
}
<form id="file-form"
action="[REPLACE-ME-WITH-URL-TO-API-GATEWAY-ENDPOINT]"
method="post" enctype="multipart/form-data">
<label for="file-input">Choose file</label>
<input type="file" name="file" id="file-input">
<button class="btn btn-primary" type="submit">
Upload
</button>
</form>
# This file will generate an API endpoint for your handler,
# using serverless (see www.serverless.com)
#
# For full config options, check the docs:
# docs.serverless.com
#
service: hello-world-functions
provider:
name: aws
runtime: python3.6
region: eu-central-1
iamRoleStatements:
- Effect: Allow
# Note: Giving full access like this is bad practice
Action:
- s3:*
Resource: "*"
functions:
helloworld:
handler: handler.save_to_bucket
events:
# Note: This API Gateway needs to be configured manually before accepting
# See http://notes.webutvikling.org/?p=747
- http:
path: helloworld/upload_to_S3
method: post
cors: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment