可以使用 base64 编码将二进制内容转换为可读的字符串,并通过 API Gateway 返回给客户端。以下是一个示例代码:
import base64
def lambda_handler(event, context):
# 读取二进制文件
with open('/path/to/file.pdf', 'rb') as f:
binary_data = f.read()
# 将二进制内容转换为 base64 编码
base64_data = base64.b64encode(binary_data).decode('utf-8')
# 构造响应
response = {
'statusCode': 200,
'isBase64Encoded': True,
'headers': {
'Content-Type': 'application/pdf',
},
'body': base64_data
}
return response
其中,isBase64Encoded
必须设置为 True
,以告知 API Gateway 返回的内容为 base64 编码的字符串。在客户端获取响应后,可以使用相应语言的 base64 解码方法将其转换为二进制内容,如 JavaScript 中的 atob()
函数。