How To Upload Images To Amazon S3 Bucket Using AngularJs


Upload Images To Amazon S3 Bucket Using AngularJs

In this tutorial, I am going to explain how to upload images to Amazon S3 bucket using AngularJs without server code.

I am not using any Rest APIs or backend services in this tutorial. It’s a front-end application which is written in AngularJs.

So What is Amazon S3?

Amazon s3 is a simple storage service provided by Amazon. We can connect our websites and applications to s3 services. We can store files and access files from anywhere directly from the cloud.

Amazon S3 provides us, the flexibility to store unlimited data in a cost-effective way. It Also provides the security of the files and user access policies to access the bucket objects.

It provides a set of libraries to integrate services on the application.

To get started with this project you should be familiar with the following technologies.

  1. HTML and CSS
  2. Javascript
  3. AngularJs

And also you should have an account on Amazon Aws. If you don’t have click here to create one.

In this tutorial, I am going to cover the following topics.

  1. Creating a bucket on Amazon S3
  2. Adding a bucket policy.
  3. Creating security credentials.
  4. Building a web page for the project.
  5. Writing the AngularJs code to bring functionality to the project.

Creating a bucket on Amazon S3

Step1: go to the Amazon S3 console.

Step2: go to All services

Step3: under All services, you see Storage section.

Step4: on the Storage section click on S3.

amazon s3

When you click on S3, you will get displayed with the following window.

In the above window, you see a Create bucket button.

Now click on the Create bucket button.

When you click on the Create bucket button, you will get displayed with the following window.

create bucket window

Step1: Type your bucket name on the Bucket name field.

Step2: Select your region from the dropdown list.

Step3: Then click on the Create button and wait for a few seconds.

After a few seconds, you will be redirected to your newly created bucket and it may look like the below picture.

new amazon s3 bucket

Now you have created your own Amazon S3 bucket.

Let’s add a privacy policy to the bucket to make bucket objects visible to the public.

Adding an Amazon S3 bucket policy

On your newly created bucket window, click on the Permissions tab.

permissions tab

Now click on Bucket Policy button.

click on bucket policy

Under the Bucket policy editor, paste the following code.

policy.json

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your_bucket_name/*"
        }
    ]
}

Note: On the Resource field, type your bucket name.

Then click on the Save button.

update bucket policy

Now your bucket objects are visible to the public.

Now we have to create the Amazon AWS security credentials.

Creating Amazon S3 security credentials

Step1: Go to the Amazon S3 console page.

Step2: On the navbar, click on your account name.

click on account name

Step3: Then click on My security credentials

click on my security credentials

On the My security credentials page, click on the Access Keys (access key ID and secret access key).

click on access keys

Now click on the Create New Access Key button.

click on access keys 

When you click on Create New Access Key, you will get created with a new access key.

new access key

Ok. Now we have set up everything for our project. Let’s write the code.

Building a web page for the project.

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr" ng-app="ImageUploadApp">
  <head>

    <meta charset="utf-8">
    <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <title>AWS image upload</title>
   <style>
      .uploadPhotosContainer{
        margin: 5px;
        padding:5%;
        border:1px solid #ccc;
      }
      .displayPhotosContainer{
        margin: 5px;
      }
    </style>

  </head>
  <body>

    
<div class="container" style="width:70%;" ng-controller="ImageUploadController">
      
<div class="photosContainer" style="text-align:center;">

          
<div class="row uploadPhotosContainer">
            <button type="button" name="button" class="btn btn-info" ngf-select ng-model="photo" >select file</button>
            <button type="button" name="button" class="btn btn-primary" ng-click="uploadPhoto(photo)">upload</button>

            
<div class="row" style="text-align:center;margin-top:10px;">
              <img ngf-thumbnail="photo" alt="" style="height:500px; width:500px;">
            </div>

          </div>


      </div>

    </div>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js" charset="utf-8"></script>

    <script src="./ng-file-upload.min.js" charset="utf-8"></script>

    <!-- amazon javascript sdk cdn file -->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.24.min.js"></script>
    <script src="./script.js" charset="utf-8"></script>
  </body>
</html>

Note: I am using the ng-file-upload plugin to make my work easier. You can find the link below.

https://github.com/danialfarid/ng-file-upload

 script.js

var app=angular.module('ImageUploadApp',['ngFileUpload']);

app.controller('ImageUploadController',['$scope','$http','Upload',function($scope,$http,Upload){
  $scope.progress=0;

  $scope.uploadPhoto=function(photo){

        //amazon aws credentials
        AWS.config.update({
            accessKeyId : 'your_access_key_id',
            secretAccessKey : 'your_secret_accessKey'
        });

        //amazon s3 region
        AWS.config.region = 'us-west-2';

        //amazon s3 bucket name
        var bucket = new AWS.S3({params: {Bucket: 'your_bucket_name'}});
        var params = {Key:   photo.name, ContentType: photo.type, Body: photo};

        bucket.upload(params).on('httpUploadProgress', function(evt) {
            //logs the image uploading progress
            console.log("Uploaded :: " + parseInt((evt.loaded * 100) / evt.total)+'%');
            var progress=parseInt((evt.loaded * 100) / evt.total);
            if(progress === 100){
              alert("photo uploaded successfully");
            }

        }).send(function(err, data) {
            if (data) {
              //displays the image location on amazon s3 bucket
              console.log(data.Location);
            }
        });

  }


}]);

Ok. Now we have finished our project.

Hoping. Now you have learned how to upload images to Amazon S3 Bucket Using AngualrJs.

Also, Try How To Create A Basic Crud Application Using AngularJs

If this article helped you, comment below as It helped me.

Thanks for reading!

Keep [email protected]

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes0
No0
Powered by Pixelbart

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *