【问题标题】:How to receive a file with an Aws Lambda (python)如何使用 Aws Lambda (python) 接收文件
【发布时间】:2019-04-09 20:17:32
【问题描述】:

我试图弄清楚如何通过 Python 中的 API 调用接收浏览器发送的文件。

允许网络客户端发送任何类型的文件(比如 .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])

【问题讨论】:

  • 我在一个 zip 文件上试过这个,但结果是存储桶中的 zip 文件损坏了
  • 检查你的压缩过程,s3是可靠的,所以只有2个地方你可能会遇到问题:文件压缩得不好,或者传输不正确
  • 我将它与 multipart/form-data 一起发布,我能够获取其他表单字段,但文件本身即使在我下载它时得到更新,我也无法再打开它。

标签: python angular amazon-web-services aws-lambda


【解决方案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"
}

您可以在正文中将文件作为 base64 值传递,并在您的 lambda 函数中对其进行解码。取如下 Python sn -p

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

【讨论】:

  • 我尝试了您的建议,但出现错误:无法解码 JSON 对象:ValueError Traceback(最后一次调用):文件“/var/task/post/post2.py”,第 16 行,在 post data = json.loads(event['body'])
猜你喜欢
  • 2018-08-03
  • 2019-02-18
  • 1970-01-01
  • 2018-02-25
  • 2017-01-29
  • 2019-02-23
  • 2020-05-18
  • 2021-01-03
  • 1970-01-01
相关资源
最近更新 更多