Upload an image to S3 bucket in ionic app

Shamique
5 min readOct 26, 2018

Hi guyz. In my previous article, I discussed about cognito user management in ionic. In this article, I’ll guide you how to upload an image from ionic app to AWS S3 bucket.

Before we begin, I recommend you to read my previous article.

Use case

  • User sign up himself and login to the app (read cognito user management).
  • Take a photo using mobile camera
  • Upload the photo to S3 bucket

Technical overview

I’ll use AWS SDK to integrate AWS services. Why I choose AWS SDK is that, it has option to upload image directly to S3. And considering the security facts, below architecture would be ideal for uploading image securely,

TL;DR; (for the impatient)

Github repo: https://github.com/shamique/s3-image-upload-in-ionic

Configuring AWS services

Note: make sure to maintain same region for all the aws service instance

Log into your AWS console,

— Cognito federated identity

  • Go to Cognito service. Then Click “Manage Identity Pools” and click “Create new identity pool”
  • Provide name for your identity pool
  • Under “Authentication providers”, select Cognito tab.
  • Type your “User Pool ID” and “App client id” and then click “Create Pool”

And then you’ll land to access permission page. Here you’ll be create new user roles for cognito identity.

You may leave the option as it is and click “Allow”. Then it will land to identity dashboard page.

— IAM Role

  • Go to “IAM” services and click Roles from left panel.
  • In the role list, select the role which we created in earlier step.
  • Click “Attach policies” and select “AmazonS3FullAccess” from the policy list.

Warning: it’s not advisable to grant complete permission for S3 bucket.

— S3 Bucket

  • Go to S3 bucket service
  • Click “Create Bucket”
  • Type “Bucket Name” and select the region.

Note: make sure to select same region for all the services.

  • You may select “Versioning” in the configure options.
  • Let other settings as it is and Click next until the bucket created.
  • Now click the created bucket from the list.
  • Go to “Permissions” tab and click “CORS configuration”
  • Add below configuration code and click save
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<ExposeHeader>ETag</ExposeHeader>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Great! We have configured all the necessary AWS services. Let’s create our ionic application.

Setup the ionic project

We have already done Cognito user management in previous article. Therefore, will use the existing code and modify it for our new requirement.

Clone this git repo to your machine: https://github.com/shamique/cognito-and-ionic

Now open the terminal and navigate to the project folder and install below dependency to the project.

npm install --save-dev @types/nodenpm install –save-dev aws-sdk

We need to add node modules entry under compiler options to work with aws-sdk. So open tsconfig.json file add below property under “compilerOptions” tag,

"typeRoots": ["node_modules/@types"]

Now let’s install camera plugin to the application,

ionic cordova plugin add cordova-plugin-cameranpm install --save @ionic-native/camera

and also, we need to add platform to the application hence we will use native camera plugin. I’ll use android in my example.

ionic cordova platform add android

Now let’s generate a new page for camera option and image upload function. And also a new service to handle all the S3 bucket function,

ionic g page image-uploadionic g provider s3-service

Now open system-variable.ts file and append SYSTEM_PARAMS object with below two properties and set appropriate values to each key.

COGNITO_IDENTITY: {
IDENTITY_POOL_ID: ""
},
S3: {
BUCKET_NAME: ""
}

Now let’s customize our login component.

Once the user authenticates, will redirect the user to image upload page. And also will add a loading indicator in the login page.

So new code for login component will be as follow,

To be in the safe side, run `ionic serve` and test the app in the browser before move into image upload function.

As of this, we have setup our project. Let’s jump to code.

Image upload and camera function

— S3 service

Open s3-service.ts file and import below items in top,

import * as aws from "aws-sdk";import { SystemVariableProvider } from "../system-variable/system-variable";

and add below upload function,

  • Update the AWS Credential with cognito identity and logged in user’s access token.

Note: in line number 7, login key’s format is
“cognito-idp.<REGION_NAME>.amazonaws.com/<USER_POOL_ID>” so replace the region name and user pool id with appropriate value

  • Since we are uploading an image, our content encoding should be base64 and content should be image/jpeg
  • In data object, key property is a unique name for the object. In this example, let’s use the input image name as the key.
  • And finally we will return the results as promise

— Image upload view

Hence our objective is to upload the captured image, let’s keep the interface as minimal. Open image-upload.html file and replace the content with below,

— Image upload component

Now open image-upload.ts and add below functions in it.

  • Camera function
  • Upload function

To work with S3, we need to get logged in user’s identity token. To get identity token, we have written a method called getLoggedUser in cognito service file. Obtain the identity token from that method and pass it to upload function along with image data and the image name.

Great! Now the coding is complete.

Time to debug.

Debug the app

Connect your android device to PC and enable debugging mode in your phone.

Now run the app,

ionic cordova run android

Take a snap and upload with a name. Then go to your S3 bucket and check.

We covered our basic scenario as mentioned in the beginning. So this is it for now. And the complete code for the article could be found in below repo,

Hope you find this useful. Thanks for reading!

(Few 👏are always appreciated 😃)

--

--

Shamique

Senior Software Engineer at 99x / Microsoft Certified Azure Developer / Photographer