Python: AWS lambda receiving form file (with serverless.yml)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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 contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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