1. Go to the list page containing Lambda functions
2. Configure the Upload Function on the Create function page
In the first section, there are 3 options to create a template for the Lambda Function: Author from scratch, Use a blueprint, Container image
In the Basic information section:
In the Change default execution role section:
3. Configure the Upload Function code in the Code Source section
import json
import boto3
import base64
import uuid
import os
# Initialize S3 client
s3 = boto3.client('s3')
# Get bucket name from environment variable (replace with your bucket name)
BUCKET = os.environ.get("BUCKET_NAME", "your-bucket-name")
def lambda_handler(event, context):
try:
# Parse body content from HTTP request (JSON format)
body = json.loads(event["body"])
# Get image data (base64) and analysis result sent from frontend
image_base64 = body.get("image")
result_data = body.get("result")
# Check if image or result is missing, return error
if not image_base64 or not result_data:
return {
"statusCode": 400,
"body": json.dumps({"error": "Missing image or result"})
}
# Decode base64 image to bytes
image_bytes = base64.b64decode(image_base64)
# Generate random image filename using UUID
filename = f"image-{uuid.uuid4()}.jpg"
# Upload original image to 'images/' folder in S3 bucket
s3.put_object(
Bucket=BUCKET,
Key=f"images/{filename}",
Body=image_bytes,
ContentType="image/jpeg"
)
# Generate corresponding JSON filename and upload analysis result to 'results/' folder
s3.put_object(
Bucket=BUCKET,
Key=f"results/{filename.replace('.jpg', '.json')}",
Body=json.dumps(result_data),
ContentType="application/json"
)
# Return success result to frontend, including image and JSON file links
return {
"statusCode": 200,
"body": json.dumps({
"message": "Upload successful",
"imageUrl": f"https://{BUCKET}.s3.amazonaws.com/images/{filename}",
"resultUrl": f"https://{BUCKET}.s3.amazonaws.com/results/{filename.replace('.jpg', '.json')}"
}),
"headers": {
"Access-Control-Allow-Origin": "*", # Allow access from any domain
"Content-Type": "application/json"
}
}
except Exception as e:
# Return 500 error if exception occurs and allow CORS
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)}),
"headers": {"Access-Control-Allow-Origin": "*"}
}
Note, please replace your bucket name, do not duplicate the bucket name
You have completed the step of configuring the Lambda Function for uploading images and analysis results