要在AWS Lambda函数中使用FormData文件上传,您可以使用以下步骤和代码示例解决问题:
import json
def lambda_handler(event, context):
# 使用event参数获取传入的请求
# 检查请求类型是否是multipart/form-data
headers = event['headers']
content_type = headers['Content-Type']
if content_type.startswith('multipart/form-data'):
# 获取文件数据
file_data = event['body']
# 处理文件数据
# 在这里可以将文件数据保存到S3存储桶等
# 返回响应
response = {
'statusCode': 200,
'body': json.dumps({'message': '文件上传成功'})
}
return response
else:
# 返回错误响应
response = {
'statusCode': 400,
'body': json.dumps({'error': '无效的请求类型'})
}
return response
{
"body" : $input.json('$'),
"headers": {
# 如果需要,添加任何其他请求标头
"Content-Type": "$input.params().header.get('Content-Type')"
}
}
现在,您可以使用FormData文件上传到Lambda函数了。确保在发送请求时设置正确的Content-Type标头,并将文件数据作为请求正文发送。
以下是使用cURL发送文件上传请求的示例:
curl -X POST \
-H "Content-Type: multipart/form-data" \
-F "file=@path/to/file.txt" \
https://your-api-gateway-url/your-endpoint
请注意将“path/to/file.txt”替换为您要上传的实际文件的路径,以及“your-api-gateway-url/your-endpoint”替换为您的API网关端点URL。
这样,您就可以在AWS Lambda函数中使用FormData文件上传了。