Reference

https://www.youtube.com/watch?v=mw_-0iCVpUc&list=PLJo-rJlep0EAY0nMNBv0MZ487l1tOFAjh&index=8

Work Steps

S3Bucket Section

  1. Create a S3 Bucket from AWS Console

  2. Configure CORS for those s3bucket to be like this (go to Permissions > Cross-origin resource sharing)

    [
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST",
            "HEAD",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
    ]
  3. Create an IAM Roles with below policies (there is two policies, the second one is inline policy) lambda3

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "arn:aws:logs:us-east-1:12345-change-to-your-accountid:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:us-east-1:2345-change-to-your-accountid:log-group:/aws/lambda/test-s3-uploader-serverless:*"
            ]
        }
    ]
}
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::your-bucket-name/*"
        }
    ]
}

Lambda Section

  1. Login to AWS Console -> Lambda -> Create Function
    *choose the previous iam role

lambda2

  1. Insert below codes to your lambda function https://github.com/aws-samples/serverless-s3-uploader/blob/master/s3UploaderFunction/app.js
/*
  Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  Permission is hereby granted, free of charge, to any person obtaining a copy of this
  software and associated documentation files (the "Software"), to deal in the Software
  without restriction, including without limitation the rights to use, copy, modify,
  merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so.
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

'use strict'

const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.AWS_REGION || 'us-east-1' })
const s3 = new AWS.S3()

// Main Lambda entry point
exports.handler = async (event) => {
  const result = await getUploadURL()
  console.log('Result: ', result)
  return result
}

const getUploadURL = async function() {
  const actionId = parseInt(Math.random()*10000000)

  const s3Params = {
    Bucket: process.env.UploadBucket,
    Key:  `${actionId}.jpg`,
    ContentType: 'image/jpeg' // Update to match whichever content type you need to upload
    //ACL: 'public-read'      // Enable this setting to make the object publicly readable - only works if the bucket can support public objects
  }

  console.log('getUploadURL: ', s3Params)
  return new Promise((resolve, reject) => {
    // Get signed URL
    resolve({
      "statusCode": 200,
      "isBase64Encoded": false,
      "headers": {
        "Access-Control-Allow-Origin": "*"
      },
      "body": JSON.stringify({
          "uploadURL": s3.getSignedUrl('putObject', s3Params),
          "photoFilename": `${actionId}.jpg`
      })
    })
  })
}
  1. Go to Configuration -> Environment variables -> Add your bucket name lambda5

  2. Deploy and test lambda function, make sure you got body response in the logs section lambda4
    lambda6
    lambda7

API Endpoint Section

  1. Add trigger for your lambda function (API Gateway) lambda8
    lambda9
    lambda10

Testing Section

  1. Open Postman
  2. Create two request and replace the API endpoint and API key detail
    2.1. GetRequest -> to get PresignedUrl
    lambda11

    2.2. PutRequest -> to test Upload
    lambda12
  3. Verify that the object is already exist in your s3bucket