我正在尝试通过 Postman 的表单上传,然后尝试通过 lambda fn 接收该图像,然后将其存储在 s3 中。
问题是:显示了文件名,但是当我下载它时,我得到了
不支持文件类型
我已授予访问 S3 和 lambda 的权限。我是 lambda 函数的新手,并试图弄清楚如何做这些事情
代码:
import json
import boto3
import base64
s3_client = boto3.client('s3')
BUCKET_NAME = 'u'
last_value = None
def lambda_handler(event, context):
global last_value
print(json.dumps(event))
# Check if the event is from API Gateway
if 'httpMethod' in event:
if event['httpMethod'] == 'POST':
try:
headers = event.get('headers', {})
body = event.get('body', '')
# If the body is base64 encoded, decode it
if event.get('isBase64Encoded', False):
body = base64.b64decode(body)
# Extract file name from headers
file_name = headers.get('file-name')
if not file_name:
raise ValueError("Missing 'file-name' header")
# The body should contain binary data directly if it's a file upload
# Upload to S3
s3_client.put_object(
Bucket=BUCKET_NAME,
Key=file_name,
Body=body.split('image/jpeg\r\n\r\n')[1], # Use the body directly as it should be binary data
ContentType='image/jpeg' # Ensure this matches the actual content type
)
last_value = file_name
print('Passed value:', last_value)
return {
'statusCode': 200,
'body': json.dumps(f'The passed value is: {last_value}')
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps(f'Error uploading file: {str(e)}')
}
elif event['httpMethod'] == 'GET':
try:
# Fetch the image from S3
file_name = last_value # Get the last uploaded file name
if not file_name:
raise ValueError("No file has been uploaded yet.")
s3_response = s3_client.get_object(Bucket=BUCKET_NAME, Key=file_name)
image_data = s3_response['Body'].read()
return {
'statusCode': 200,
'isBase64Encoded': True,
'headers': {
'Content-Type': 'image/jpeg' # or 'image/png' based on your use case
},
'body': base64.b64encode(image_data).decode('utf-8')
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps(f'Error fetching image: {str(e)}')
}
# Check if the event is from S3
elif 'Records' in event and event['Records'][0]['eventSource'] == 'aws:s3':
for record in event['Records']:
bucket_name = record['s3']['bucket']['name']
object_key = record['s3']['object']['key']
print(f"File uploaded to bucket: {bucket_name}, Key: {object_key}")
return {
'statusCode': 200,
'body': json.dumps('S3 Event processed successfully.')
}
更好的方法是这个用例。调用对 API Gateway 的调用,该调用将反过来调用 Lambda 函数,该函数调用创建预签名 URL 的 S3 操作。
使用该 URL 将图像直接上传到 S3 存储桶。比尝试通过 Lambda 函数强制将图像从 Postman 传输到 S3 好得多。