我无法让 python lambda 返回二进制数据。 缩略图的节点模板 工作正常,但我无法让 python lambda 工作。以下是我的 lambda 中的相关行。 print("image_data " + image_64_encode)
行将 base64 编码图像打印到日志中。
def lambda_handler(event, context):
img_base64 = event.get('base64Image')
if img_base64 is None:
return respond(True, "No base64Image key")
img = base64.decodestring(img_base64)
name = uuid.uuid4()
path = '/tmp/{}.png'.format(name)
print("path " + path)
image_result = open(path, 'wb')
image_result.write(img)
image_result.close()
process_image(path)
image_processed_path = '/tmp/{}-processed.png'.format(name)
print("image_processed_path " + image_processed_path)
image_processed = open(image_processed_path, 'rb')
image_processed_data = image_processed.read()
image_processed.close()
image_64_encode = base64.encodestring(image_processed_data)
print("image_data " + image_64_encode)
return respond(False, image_64_encode)
def respond(err, res):
return {
'statusCode': '400' if err else '200',
'body': res,
'headers': {
'Content-Type': 'image/png',
},
'isBase64Encoded': 'true'
}
任何指向我做错了什么的指示?
原文由 Horv 发布,翻译遵循 CC BY-SA 4.0 许可协议
遵循上述所有步骤对我的情况不起作用,因为对 content-type =
*/*
的二进制支持会将所有响应转换为二进制。我的情况:
多个 lambda 函数返回 json(文本),只有一个 lambda 返回二进制文件。都启用了 lambda 代理。
lambda 在 API 网关中
API 网关在 CloudFront 后面
提示: 我注意到 API 网关 -> 设置中的重要信息
报价:
这意味着 Content-Type 响应标头必须匹配 Accept 请求标头
解决方案:
将 API 网关中的二进制媒体类型设置为您的 mime 类型:image/jpg
在您的 HTTP 请求集
Accept: image/jpg
在您的 HTTP 响应集中
Content-Type: image/jpg
custom: apigwBinary: types: - ‘image/jpeg’
resources: WebAppCloudFrontDistribution: Type: AWS::CloudFront::Distribution Properties: DistributionConfig: … CacheBehaviors: … - #API calls … ForwardedValues: … Headers: - Authorization - Accept
”`