DEV Community

Arnob
Arnob

Posted on

How To Read S3 File/Image Using Lambda Functions

Here i share how you preview image using API Gateway, S3 and Lambda Function. This function build on Node.js 18.x

AWS Lambda Function

Create A Lambda Function

captionless image

Give a function name, Runtime, Architecture.

captionless image

After creating the function. Need to Add trigger with S3 and API Gateway

Add Trigger at S3 and API Gateways

Here 1st i adding S3 as a trigger with this function.

captionless image

Give the selected bucker name and event type. After that click Add.

2nd adding the API Gateway

captionless image

At API Gateway, create intent as a create a new API , Set API Type is HTTP API , At Security, Select Open. Then Click Add Button.

Trigger configuration done.

Adding Code

Now Add Code at index.js

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event, context) => {

  const bucketName = '<BUCKET_NAME>';
  const imageKey = '<IMAGE_KEY/NAME>'; // Replace 'your-image-key.jpg' with your actual image key

  try {
    const params = {
      Bucket: bucketName,
      Key: imageKey,
    };

     const s3Object = await s3.getObject(params).promise();
    if (!s3Object || !s3Object.Body) {
      return {
        statusCode: 404,
        body: JSON.stringify({ message: 'Image not found' })
      };
    }
    const imageData = Buffer.from(s3Object.Body, 'binary').toString('base64') ;
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'image/jpeg'
      },
      isBase64Encoded: true,
      body: imageData

    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify(error.message)
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

Here a a require package needed. But you can’t add node_modules at Lambda function. Need to create a layer.

Goto Lambda Function > Layer (At Additional resources)

captionless image

Creating a layer

captionless image

Give a function name, upload the zip file, select the Compatible architectures and select the compatible runtimes. Then Create Layer.

captionless image

After that, you need to add that layer to lambda function.

Adding Layer

At the Code Section, the bottom you find the Layers section.

captionless image

Click Add a layer

captionless image

Select Custom Layers, there it shows your created layers. Add that layer then click Add Button.

captionless image

Then 1 layer has added.

Now goto Configuration > Click Triggers

captionless image

Here you see a API Gateway endpoint and S3 bucket

When you click the link, you see the image,

captionless image

Happy Coding…

Here a Payoneer Refer Link

Top comments (0)