How to upload Images to Amazon S3 using Angularjs


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. It provides us a flexibility to store unlimited data and cost-effective way “Pay as you use”. 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.

In this tutorial, we are going to implement the functionality on How to upload images to Amazon S3  using Angularjs without server code.

creating bucket on amazon s3

Go to Amazon s3 Console . Then go to all services -> storage  then click on s3

Now Click on Create Bucket Button.

By Clicking on create bucket button you will get displayed with a form to create a bucket.

In the form fields type your Bucket name and select Region then click on Create.

After a few seconds, you will see your newly created bucket in the amazon s3 console.

You need to make your bucket access to public. otherwise you can’t access your files via web browser.

Open your bucket and go to permissions and their click on bucket policy.

 

under bucket policy type the code which is give below.

policy.json

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

 

And click on save button. Now your files in this bucket will be public access.

Let’s write a code to implement the functionality to upload images to amazon s3 bucket.

In this tutorial I am using ng-file-upload plugin to make my work eaiser. you can find the link below.

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

And also you need an aws security credentials. To find security credentials go to amazon console and click on your account name and  click on my security credentials.

and click on Create New Access Key  button

Click on Download Key File or Show Access Key to find your Credentials.

That’s it for the setup

Let’s start coding…

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>

 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);
            }
        });

  }


}]);

Hope It may helpful to you. If you have any queries please comment below.


1 Comment

Leave a Reply

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