Close

AWS S3 integration with ionic


I am creating one Wallpaper app and I have chosen AWS S3 bucket to store my wallpaper images. I have created some folders on S3 root for different wallpaper categories and inside each folder I have uploaded my images.

 

Now, I have to access my S3 bucket from my ionic app. Below are the steps how I installed the AWS SDK and access it with ionic.

 

Before installing AWS-SDK please make sure your app is running and working correct.

 

          ionic serve

  
1. Install the AWS SDK for Java Script

     npm install aws-sdk        

  2. Add new provider for s3 operations. I am giving the name ‘s3-manager

     ionic g provider s3-manager               

  3. Add this provider in your app module. Open app.module.ts file and import this.

     Import {S3Manager} from ‘../providers/s3-manager’;       

  4. Open your s3-manager.ts file and import AWS SDK at top.

     import AWS = require('aws-sdk');               

Run the project once to make sure import is correct. Ionic serve. You might be getting ‘Buffer’ issue first time.

  typescript: node_modules/aws-sdk/clients/acm.d.ts, line: 108 
  Cannot find name 'Buffer'.

run this command:

     npm install --save-dev @types/node

run app again to make sure import is correct. If you are getting error like.

  // Import assignment cannot be used when targeting ECMAScript 2015 modules.

open tsconfig.json

for `module` key, set the value `commonjs`

save the file and build again. Everything should be correct.


Now, write some code to access your S3 bucket.

         public awsSetup()
         {
         var credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: “Your-Cognito-Pool-id” });

         AWS.config.credentials = credentials;
         AWS.config.region = ‘Your-region (e.g. us-west-2)’;
         var s3 = new AWS.S3();

         let params = {
         Bucket: ‘Your-Bucket-Name’,
         Delimiter: '/'
         };
        // Delimiter is used to show only root files/folders of the bucket. Suppose you have your          bucket structure something like this:

        //directory1/
       //directory2/directory/
      //directory3/directory/file
     //directory4/file
    //file
   // If you want all directories and there inside files, remove delimiter from param. Otherwise by using delimiter output will be like:

     //directory1/
    //directory2/
   //directory3/
   //directory4/
  //file

 // console.log (JSON.stringify(params));

 s3.listObjects(params, function(error, data)
  {
  if (error)
  console.log(error, error.stack); // an error occurred

  else
  console.log(JSON.stringify(data));

  // You will get the key 'CommonPrefixes' which have all folder names of bucket.
  // You need to remove / from end of folder name.
  });
  }

After this import your provider class in your main class or from where you want to access. and call the method awsSetup( ). Like i import this in my Home.ts file.

    import {S3Manager} from '../../providers/s3-manager';

    export class HomePage {
    constructor(publicnavCtrl:NavController, publics3Object:S3Manager) {                  
    s3Object.s3Setup();
     } 

         }

 

When you run the app again, You might get network error. Something like:

    error opening ws message:
     {"category":"console","type":"log","data":
[{"line":126135,"column":43,"sourceURL":"http://localhost:8100/build/main. js","code":"NetworkingError","message":"Network Failure","time":"2017-07-11T19:35:23.155Z","region":"us-west-2","hostname”:”your-bucket.s3-us-west-2.amazonaws.com","retryable":true},"http://localhost:8100/build/main.js:126135:43\ninvokeTask@http://localhost:8100/build/polyfills.js:3:9728\nonInvokeTask@http://localhost:8100/build/main.js:46333:47\ninvokeTask@http://localhost:8100/build/polyfills.js:3:9671\nrunTask@http://localhost:8100/build/polyfills.js:3:7093\ninvoke@http://localhost:8100/build/polyfills.js:3:10843"]}
     

This error shows, your bucket CORS configuration is not setup correctly for web pages.

To add a CORS configuration to an S3 bucket

  •  Sign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/.
  • In the Bucket name list, choose the name of the bucket that you want to create a bucket policy for.
  • Choose Permissions, and then choose CORS configuration.
  • In the CORS configuration editor text box, type or copy and paste a new CORS configuration, or edit an existing configuration. The CORS configuration is a XML file. The text that you type in the editor must be valid XML.
        <?xml version="1.0" encoding="UTF-8"?> 
        <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> 
        <CORSRule>           
        <AllowedOrigin>http://*</AllowedOrigin> 
        <AllowedOrigin>https://*</AllowedOrigin>        
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod> 
        <AllowedMethod>PUT</AllowedMethod> 
        <AllowedHeader>*</AllowedHeader>
        </CORSRule>
        </CORSConfiguration>

Choose Save.

Go back to terminal and run ionic serve again to re-launch the app.

       ionic serve -c
        // -c to print console logs on terminal

Now you will get list of root files and folders of your bucket. You can access the files by giving full file path. Make sure you have set the correct ACL property of your bucket folders.

 

Reference documents:

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html

http://docs.aws.amazon.com/AmazonS3/latest/user-guide/add-cors-configuration.html

 

You can download the sample code from my git account.

 

Still facing any issue with ionic development? Or want to be in touch with us? Contact us at: support@triffort.com

 

 

 

 

Triffort Technologies Pvt Ltd
www.triffort.com

 

 

0 Comments

Leave a reply

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

Comment

Name

Email

Social Comments
Go top