Uploading File from Browser to S3 with JavaScript
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: AWS, Cognito, JavaScript, S3, Serverless
Uploading a file from a browser to S3 for only authorised users is a pretty cool trick. It is even cooler if we can build it in a serverless way. Here is the entire solution for a simple serverless app to authenticate with AWS Cognito and upload a file to S3 through IAM role assigned to the authenticated user.
For serverless user authentication with Cognito, check out the post here. This post focuses on client-side JavaScript to enable S3 uploading.
As mentioned in the previous post, the most important concept with AWS Cognito is User Pool and Identity Pool. User Pool manages authentication while Identity Pool manages authorisation to AWS resources through IAM role.
To enable S3 upload, we need to assign IAM policy that enables S3 upload to the authenticated user.
As the file is uploaded through AJAX call from a browser, we need to enable CORS on the target S3 bucket.
When you have the right IAM policy to access the bucket and enable CORS, you are pretty much ready. The cool thing about this is that you can trigger a lambda function on S3 upload event and further do data processing, then bring back the result with another lambda function. The possibility is endless!
Dependencies
We can simply import aws-sdk-js in the script tag at the end of the body. We also need to use another SDK, amazon-cognito-identity, which is part of aws-amplify. Here is the example of html file.
Set Credential
We first need to set credential from the cognito user. This will give the browser access to S3 bucket. Cognito user can be retrived by getCurrentUser().
Upload Code
This is based on AWS official documentation with an example of photo upload. Once you set up Identity pool, you can retrieve the identity pool id from Sample Code section on the identity pool dashboard. The rest is super simple. Here is the entire code that does file checking and produce modal message accordingly.