简体   繁体   English

如何从 AWS Lambda API 网关返回字节数组?

[英]How to return byte array from AWS Lambda API gateway?

I am a beginner so I am hoping to get some help here.我是初学者,所以我希望在这里得到一些帮助。

I want create a lambda function (written in Python) that is able to read an image stored in S3 then return the image as a binary file (eg. a byte array).我想创建一个 lambda function (用 Python 编写),它能够读取存储在 S3 中的图像,然后将图像作为二进制文件(例如字节数组)返回。 The lambda function is triggered by an API gateway. lambda function 由 API 网关触发。

Right now, I have setup the API gateway to trigger the Lambda function and it can return a hello message.现在,我已经设置了 API 网关来触发 Lambda function 并且它可以返回一个问候消息。 I also have a gif image stored in a S3 bucket.我还有一个存储在 S3 存储桶中的 gif 图像。

import base64
import json
import boto3

s3 = boto.client('s3')

def lambda_handler(event, context):
# TODO implement
bucket = 'mybucket'
key = 'myimage.gif'

s3.get_object(Bucket=bucket, Key=key)['Body'].read()
return {
    "statusCode": 200,
    "body": json.dumps('Hello from AWS Lambda!!')
}

I really have no idea how to continue.我真的不知道如何继续。 Can anyone advise?任何人都可以建议吗? Thanks in advance!提前致谢!

you can return Base64 encoded data from your Lambda function with appropriate headers.您可以使用适当的标头从 Lambda function 返回 Base64 编码数据。

Here the updated Lambda function:这里更新的 Lambda function:

import base64
import boto3

s3 = boto3.client('s3')


def lambda_handler(event, context):
    bucket = 'mybucket'
    key = 'myimage.gif'

    image_bytes = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

    # We will now convert this image to Base64 string
    image_base64 = base64.b64encode(image_bytes)

    return {'statusCode': 200,
            # Providing API Gateway the headers for the response
            'headers': {'Content-Type': 'image/gif'},
            # The image in a Base64 encoded string
            'body': image_base64,
            'isBase64Encoded': True}

For further details and step by step guide, you can refer to this official blog .有关详细信息和分步指南,您可以参考此官方博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM