// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using System;
using Amazon.Lambda.S3Events;
using System.Web;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespaceS3Integration{publicclassFunction{privatestatic AmazonS3Client _s3Client;
publicFunction() : this(null){
}
internalFunction(AmazonS3Client s3Client){
_s3Client = s3Client ?? new AmazonS3Client();
}
publicasync Task<string> Handler(S3Event evt, ILambdaContext context){try{if (evt.Records.Count <= 0)
{
context.Logger.LogLine("Empty S3 Event received");
returnstring.Empty;
}
var bucket = evt.Records[0].S3.Bucket.Name;
var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);
context.Logger.LogLine($"Request is for {bucket} and {key}");
var objectResult = await _s3Client.GetObjectAsync(bucket, key);
context.Logger.LogLine($"Returning {objectResult.Key}");
return objectResult.Key;
}
catch (Exception e)
{
context.Logger.LogLine($"Error processing request - {e.Message}");
returnstring.Empty;
}
}
}
}
import{ S3Client, HeadObjectCommand } from"@aws-sdk/client-s3";
const client = new S3Client();
exportconst handler = async (event, context) => {// Get the object from the event and show its content typeconst bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
try{const{ ContentType } = await client.send(new HeadObjectCommand({Bucket: bucket,
Key: key,
}));
console.log('CONTENT TYPE:', ContentType);
return ContentType;
} catch (err) {console.log(err);
const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
console.log(message);
thrownewError(message);
}
};
TypeScript を使用して Lambda で S3 イベントを消費する。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.// SPDX-License-Identifier: Apache-2.0import{ S3Event } from'aws-lambda';
import{ S3Client, HeadObjectCommand } from'@aws-sdk/client-s3';
const s3 = new S3Client({region: process.env.AWS_REGION });
exportconst handler = async (event: S3Event): Promise<string | undefined> => {// Get the object from the event and show its content typeconst bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
const params = {Bucket: bucket,
Key: key,
};
try{const{ ContentType } = await s3.send(new HeadObjectCommand(params));
console.log('CONTENT TYPE:', ContentType);
return ContentType;
} catch (err) {console.log(err);
const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
console.log(message);
thrownewError(message);
}
};
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: Apache-2.0import json
import urllib.parse
import boto3
print('Loading function')
s3 = boto3.client('s3')
deflambda_handler(event, context):#print("Received event: " + json.dumps(event, indent=2))# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
try:
response = s3.get_object(Bucket=bucket, Key=key)
print("CONTENT TYPE: " + response['ContentType'])
return response['ContentType']
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e
require'json'require'uri'require'aws-sdk'
puts 'Loading function'deflambda_handler(event:, context:)
s3 = Aws::S3::Client.new(region:'region') # Your AWS region# puts "Received event: #{JSON.dump(event)}"# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8)
begin
response = s3.get_object(bucket: bucket, key: key)
puts "CONTENT TYPE: #{response.content_type}"return response.content_type
rescue StandardError => e
puts e.message
puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function."
raise e
endend
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.// SPDX-License-Identifier: Apache-2.0use aws_lambda_events::event::s3::S3Event;
use aws_sdk_s3::{Client};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};
/// Main function#[tokio::main]asyncfnmain() -> Result<(), Error> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.with_target(false)
.without_time()
.init();
// Initialize the AWS SDK for Rustlet config = aws_config::load_from_env().await;
let s3_client = Client::new(&config);
let res = run(service_fn(|request: LambdaEvent<S3Event>| {
function_handler(&s3_client, request)
})).await;
res
}
asyncfnfunction_handler(
s3_client: &Client,
evt: LambdaEvent<S3Event>
) -> Result<(), Error> {
tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS");
if evt.payload.records.len() == 0{
tracing::info!("Empty S3 event received");
}
let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist");
let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist");
tracing::info!("Request is for {} and object {}", bucket, key);
let s3_get_object_result = s3_client
.get_object()
.bucket(bucket)
.key(key)
.send()
.await;
match s3_get_object_result {Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"),
Err(_) => tracing::info!("Failure with S3 Get Object request")
}
Ok(())
}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using System;
using Amazon.Lambda.S3Events;
using System.Web;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespaceS3Integration{publicclassFunction{privatestatic AmazonS3Client _s3Client;
publicFunction() : this(null){
}
internalFunction(AmazonS3Client s3Client){
_s3Client = s3Client ?? new AmazonS3Client();
}
publicasync Task<string> Handler(S3Event evt, ILambdaContext context){try{if (evt.Records.Count <= 0)
{
context.Logger.LogLine("Empty S3 Event received");
returnstring.Empty;
}
var bucket = evt.Records[0].S3.Bucket.Name;
var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);
context.Logger.LogLine($"Request is for {bucket} and {key}");
var objectResult = await _s3Client.GetObjectAsync(bucket, key);
context.Logger.LogLine($"Returning {objectResult.Key}");
return objectResult.Key;
}
catch (Exception e)
{
context.Logger.LogLine($"Error processing request - {e.Message}");
returnstring.Empty;
}
}
}
}