![](/img/trans.png)
[英]How to access a yaml file uploaded to a layer in a python aws lambda
[英]How to receive a file with an Aws Lambda (python)
我正試圖弄清楚如何通過Python中的API調用接收瀏覽器發送的文件。
允許Web客戶端發送任何類型的文件(例如.txt,.docx,.xlsx,...)。 我不知道我是否應該使用二進制文件。
想法是在S3之后保存文件。 現在我知道可以使用像Aws Amplify這樣的js庫並生成一個臨時URL,但我對這個解決方案不太感興趣。
任何幫助表示贊賞,我已經在Python中廣泛搜索了一個解決方案,但我找不到任何實際工作的東西!
我的API是私有的,我使用無服務器進行部署。
files_post:
handler: post/post.post
events:
- http:
path: files
method: post
cors: true
authorizer:
name: authorizer
arn: ${cf:lCognito.CognitoUserPoolMyUserPool}
編輯
我有一個半解決方案適用於文本文件但不適用於PDF,XLSX或圖像,如果有人讓我超級開心
from cgi import parse_header, parse_multipart
from io import BytesIO
import json
def post(event, context):
print event['queryStringParameters']['filename']
c_type, c_data = parse_header(event['headers']['content-type'])
c_data['boundary'] = bytes(c_data['boundary']).encode("utf-8")
body_file = BytesIO(bytes(event['body']).encode("utf-8"))
form_data = parse_multipart(body_file, c_data)
s3 = boto3.resource('s3')
object = s3.Object('storage', event['queryStringParameters']['filename'])
object.put(Body=form_data['upload'][0])
您正在使用API網關,因此您的lambda事件將映射到類似的內容(來自Amazon Docs ):
{
"resource": "Resource path",
"path": "Path parameter",
"httpMethod": "Incoming request's method name"
"headers": {String containing incoming request headers}
"multiValueHeaders": {List of strings containing incoming request headers}
"queryStringParameters": {query string parameters }
"multiValueQueryStringParameters": {List of query string parameters}
"pathParameters": {path parameters}
"stageVariables": {Applicable stage variables}
"requestContext": {Request context, including authorizer-returned key-value pairs}
"body": "A JSON string of the request payload."
"isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}
您可以將文件作為base64值傳遞到正文中,並在lambda函數中對其進行解碼。 獲取以下Python代碼段
def lambda_handler(event, context):
data = json.loads(event['body'])
# Let's say we user a regular <input type='file' name='uploaded_file'/>
encoded_file = data['uploaded_file']
decoded_file = base64.decodestring(encoded_file)
# now save it to S3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.