Step 1: Create an AWS Lambda function
- Go to the AWS Lambda console.
- Click Create function.
- Choose Author from scratch.
- Configure your function:
- Function Name: Choose a name for your Lambda function.
- Runtime: Select a runtime,We will use Node in this tutorial. (Node latest version).
- Execution Role: Create a new role for Lambda service with permissions to access S3. This role should have an IAM policy allowing PutObject and ReadObject access to the S3 bucket. For simplicity we will choose AmazonS3FullAccess. Do not use this in production environment.
- Under Advanced settings, select Enable function URL and Auth type as NONE. Leave the rest as default.
- Click Create function.
Step 2: Write the Lambda function code
/* We will pass the file name in the request to the lambda
* function and that will be used to create the object key. If no
* file name is provided we will fallback to a hardcoded filename
* for simplicity. You can throw a validation error if no filename
*is passed in request as query param
*/
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import {getSignedUrl} from "@aws-sdk/s3-request-presigner";
export const handler = async (event) => {
const region = 'your-region';
const bucket = 'your-bucket';
const queryStringParameters = event.queryStringParameters;
var key = "test";
if (queryStringParameters) {
key = queryStringParameters.filename;
}
return createPresignedUrlWithClient({region,bucket,key});
};
const createPresignedUrlWithClient = ({ region, bucket, key }) => {
const client = new S3Client({ region });
const command = new PutObjectCommand({ Bucket: bucket, Key: key });
return getSignedUrl(client, command, { expiresIn: 3600 });
};
Step 3: Create an S3 bucket
- Go to the AWS S3 console.
- Click Create bucket.
- Enter a name for your bucket.
- Select a region for your bucket.
- Click Create.
Step 4: Update the CORS policy for the S3 bucket
- Go to the Properties tab for your S3 bucket.
- Click Edit CORS configuration.
- Add the following CORS policy and Click Save. Again for simplicity we will allow all origins. But in production this has to be revisited to allow only the required origin.
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
Step 5: Test the Lambda function
- Enter the Function URL in a postman/Curl GET request with filename as query parameter.
- The response will be a presigned URL that you can use to upload a file to the S3 bucket.
- Upload a file using the URL in postman/Curl by choosing PUT request type.
Conclusion
In this blog post, we showed you how to create a Lambda function that generates a presigned URL for S3 upload. We also showed you how to create an S3 bucket and update the CORS policy for the bucket.
Top comments (0)