dar*_*rse 5 python amazon-s3 amazon-web-services aws-lambda
我正在尝试从 S3 存储桶获取图像并将其返回。这是代码:
import base64
import boto3
import json
import random
s3 = boto3.client('s3')
def lambda_handler(event, context):
number = random.randint(0,1)
if number == 1:
response = s3.get_object(
Bucket='bucket-name',
Key='image.png',
)
image = response['Body'].read()
return {
'headers': { "Content-Type": "image/png" },
'statusCode': 200,
'body': base64.b64encode(image).decode('utf-8'),
'isBase64Encoded': True
}
else:
return {
'headers': { "Content-type": "text/html" },
'statusCode': 200,
'body': "<h1>This is text</h1>",
}
Run Code Online (Sandbox Code Playgroud)
当我到达终点时,会返回一个白色小盒子的图像。我知道image.png我的存储桶中存在该图像,当我使用 Web GUI 在浏览器中打开它时,图像会正确加载。我到底做错了什么?如果重要的话,我将图像上传到 S3(从另一个 Lambda)的方式如下:
...
# Prepare image for S3
buffer = io.BytesIO()
my_image.save(buffer, 'PNG')
buffer.seek(0) # Rewind pointer back to start
response = s3.put_object(
Bucket=S3_BUCKET_NAME,
Key=f'{S3_KEY}{filename}.png',
Body=buffer,
ContentType='image/png',
)
...
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,my_image只是我使用该PIL库创建的图像。
谢谢你的帮助!
这是我的做法:
您的 lambda 已更正body:
import base64
import boto3
import json
import random
s3 = boto3.client('s3')
def lambda_handler(event, context):
response = s3.get_object(
Bucket='bucket-name',
Key='image.png',
)
image = response['Body'].read()
return {
'headers': { "Content-Type": "image/png" },
'statusCode': 200,
'body': base64.b64encode(image),
'isBase64Encoded': True
}
Run Code Online (Sandbox Code Playgroud)
API网关设置
整合请求
| 归档时间: |
|
| 查看次数: |
3130 次 |
| 最近记录: |