如何使用 Aws Lambda (python) 接收文件

Tib*_*ibo 9 python amazon-web-services aws-lambda angular

我试图弄清楚如何通过 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}
Run Code Online (Sandbox Code Playgroud)

编辑

我有一个适用于文本文件但不适用于 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])
Run Code Online (Sandbox Code Playgroud)

yor*_*odm -1

您正在使用 API Gateway,因此您的 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"
}
Run Code Online (Sandbox Code Playgroud)

您可以将文件作为正文中的 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
Run Code Online (Sandbox Code Playgroud)