Amazon S3 trigger to invoke a Lambda function

Using an Amazon S3 trigger to invoke a Lambda function

The Lambda function retrieves the source S3 bucket name and the key name of the uploaded object from the event parameter that it receives. The function uses the Amazon S3 getObject API to retrieve the content type of the object.

Select language:

Usage Example with Node:

Consuming an S3 event with Lambda using JavaScript.

const aws = require('aws-sdk');

const s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = async (event, context) => {
    // Get the object from the event and show its content type
    const 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.headObject(params).promise();
        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);
        throw new Error(message);
    }
};

                                                      



Created by:

David Boyne

David Boyne

Helping people learn about event-driven architectures and serverless

Follow on LinkedIn

James Eastham

James Eastham

I am a Cloud Infrastructure Architect with AWS Professional Services.

Rahul Popat

Rahul Popat

Senior Specialist Solutions Architect at AWS

Follow on LinkedIn

Brian Krygsman

Brian Krygsman

Solutions Architect at AWS