如果使用 CGI,我建议使用 FieldStorage:
from cgi import FieldStorage
fs = FieldStorage(fp=event['body'], headers=event['headers'], environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':event['headers']['Content-Type'], })['file']
originalFileName = fs.filename
binaryFileData = fs.file.read()
另见:
https://stackoverflow.com/a/38718958/10913265
如果事件正文包含多个文件:
fs = FieldStorage(fp=event['body'], headers=event['headers'], environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':event['headers']['Content-Type'], })['file']
提供 FieldStorage 对象的列表。所以你可以这样做:
for f in fs:
originalFileName = f.filename
binaryFileData = f.file.read()
总的来说,我处理单个文件和多个文件以及包含无文件的正文的解决方案并确保它是 mutlipart/form-data:
from cgi import parse_header, FieldStorage
#see also: https://stackoverflow.com/a/56405982/10913265
c_type, c_data = parse_header(event['headers']['Content-Type'])
assert c_type == 'multipart/form-data'
#see also: https://stackoverflow.com/a/38718958/10913265
fs = FieldStorage(fp=event['body'], headers=event['headers'], environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':event['headers']['Content-Type'], })['file']
#If fs contains a single file or no file: making FieldStorage object to a list, so it gets iterable
if not(type(fs) == list):
fs = [fs]
for f in fs:
originalFileName = f.filename
#no file:
if originalFileName == '':
continue
binaryFileData = f.file.read()
#Do something with the data