AWS Lambda函数返回S3存储桶图片时文件损坏问题咨询
核心错误点
- 重复编码+编码类型不匹配:你先对S3读取的原始图片字节做了
base64.b64encode,接着又对base64编码后的结果做了base64.b85encode,两次无意义编码导致原始图片字节被完全转成了不符合预期的内容。 - Lambda响应规则不符合:当你把
IsBase64Encoded设为True时,AWS API网关要求body字段必须是直接的base64编码字符串,而你将编码内容套在了JSON结构里,还做了base85转码,完全不符合响应规范。 - 响应头和返回内容不匹配:你设置了
Content-Type: image/jpeg,但实际返回的是JSON格式文本,内容类型完全不对应。
修复后的Lambda代码(直接返回图片)
import boto3 import base64 def get_file(file): s3 = boto3.client('s3') bucket = 'my_bucket' # 直接读取S3文件原始字节 img_bytes = s3.get_object(Bucket=bucket, Key=file)['Body'].read() headers = { 'Content-Type': 'image/jpeg' } response = { 'statusCode': 200, 'IsBase64Encoded': True, # body直接传base64编码后的字符串,不需要套json,也不需要额外base85编码 'body': base64.b64encode(img_bytes).decode('utf-8'), 'headers': headers } return response
对应直接返回图片的接收端代码
API网关会自动将base64编码的内容解码为原始图片字节,直接保存响应内容即可:
import requests # 请求Lambda接口 resp = requests.get("你的Lambda接口地址") with open('image.jpeg','wb') as f: f.write(resp.content)
如果你确实需要返回JSON格式嵌套图片内容,参考以下适配方案:
适配JSON返回的Lambda修改版
import boto3 import base64 import json def get_file(file): s3 = boto3.client('s3') bucket = 'my_bucket' img_bytes = s3.get_object(Bucket=bucket, Key=file)['Body'].read() headers = { 'Content-Type': 'application/json' } response = { 'statusCode': 200, 'IsBase64Encoded': False, 'body': json.dumps({'file': base64.b64encode(img_bytes).decode('utf-8')}), 'headers': headers } return response
对应JSON返回的接收端代码
import requests import base64 resp = requests.get("你的Lambda接口地址") file_b64 = resp.json()['file'] img_bytes = base64.b64decode(file_b64) with open('image.jpeg','wb') as f: f.write(img_bytes)
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

