在Integration Request中,从API Gateway代理集成的Lambda函数中传递的event对象中,文件内容被编码为Base64字符串。Lambda函数需要将Base64字符串解码并将文件内容存储到临时文件中。可以使用Python中的mimetypes库来确定文件的MIME类型,示例代码如下:
import base64
import mimetypes
import tempfile
def lambda_handler(event, context):
# 从API Gateway传递的event对象中获取上传文件的Base64编码字符串
encoded_file_content = event["body"]
# 将Base64编码字符串解码为文件内容
file_content = base64.b64decode(encoded_file_content)
# 将文件内容存储到临时文件中
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(file_content)
temp_file.close()
# 使用mimetypes库确定文件MIME类型
mime_type, encoding = mimetypes.guess_type(temp_file.name)
# 在Lambda函数中进行后续操作
...
在Lambda函数的event对象中,文件内容已经作为字节流直接传递。可以使用Python中的mimetypes库来确定文件的MIME类型,示例代码如下:
import mimetypes
def lambda_handler(event, context):
# 从Lambda函数的event对象中获取上传文件的字节流
file_content = event["body"]
# 使用mimetypes库确定文件MIME类型
mime_type, encoding = mimetypes.guess_type("file.txt", file_content)
# 在Lambda函数中进行后续操作
...
注意:在使用mimetypes库确定文件MIME类型时,需要传递文件名和文件内容。如果文件名不是必需的,可以传递一个任意的字符串作为文件名。