How to upload files to aws s3 using nodejs lambda and api gateway 2022

How to upload files to aws s3 using nodejs lambda and api gateway 2022

Braincuber Technologies's photo
Braincuber Technologies
·Mar 21, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

You are looking for how to upload files to AWS s3 using nodejs lambda than you are at right place

before creating lambda function, you need to create api gateway for lambda function and then create lambda function and connect our api gateway to lambda function

you can see our api gateway in image down below

upload files to aws s3 using nodejs lambda and api gateway .png

first go to lambda and create new function and write down the following code

const AWS = require('aws-sdk');
AWS.config.update({ region: process.env.AWS_REGION });
const s3 = new AWS.S3();
const { v4: uuidv4 } = require('uuid');
const URL_EXPIRATION_SECONDS = 300;

 //Main Lambda entry point
exports.handler = async (event) => {
  return await getUploadURL(event);
};

const getUploadURL = async function(event) {
  console.log('event : ',event);
  const Key = uuidv4(); 

  //Get signed URL from S3
  const s3Params = {
    Bucket: 'bucketname',
    Key:`url-name/{Key}`,
    Expires: URL_EXPIRATION_SECONDS,
    ACL:'public-read'
  };
  const uploadURL = await s3.getSignedUrlPromise('putObject', s3Params);

  const response = {
        statusCode: 200,
        "headers": {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
        "Access-Control-Allow-Headers": "x-access-token, Origin, X-Requested-With, Content-Type, Accept"
    },
        body: JSON.stringify({
          uploadURL: uploadURL,
          Key : `https://name.s3.ap-south-1.amazonaws.com/${Key}`
        })
    };

    return response

};

postman response

lambda-api-gatway-response.png

after getting response copy upload url and make put request and upload image to url now you can see that you have successfully upload file to aws s3 using lambda nodejs

also you can store key to your database, so you can access your image

if you want code for storing your key to hasura database than comment me i will provide you

if you like our guide on How to upload files to aws s3 using nodejs lambda and api gateway than follow our blog for more such useful content

Did you find this article valuable?

Support Braincuber Technologies by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this