File Uploading On AWS Server

Amazon web services provide us multiple services like Storage, Database, Application integration, etc.

Today let’s talk about the S3 service which is providing storage to upload your documents like global server storage. If you just want to use the S3 server directly(using IAM user) without cognito authentication then you just need to follow the few steps given below:

  1. Create an AWS account and create an IAM user to access S3 server.
  2. Create a Bucket in S3 server where you want to upload your document(You can create multiple buckets for groupism).
  3. Get the Accesskey and SecretKey from the console of your account which is required for the document uploading.

So the configuration of the project is done, Let’s move to the development part:

  • Add the dependencies in App level build.gradle
implementation 'com.amazonaws:aws-android-sdk-s3:2.16.4'
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.17.1@aar'){ transitive = true; }
  • Add permissions and services in manifest.xml
<uses-permission-sdk-23 android:name="android.permission.INTERNET" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_WIFI_STATE" />

<application
...>

<service
android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
android:enabled="true"/>

</application>
  • Create a Global class to upload the file on S3 server so that you can use it from multiple activity or fragment :
import android.content.Context
import android.util.Log
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.mobileconnectors.s3.transferutility.*
import com.amazonaws.regions.Region
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.CannedAccessControlList
import com.urgidoctor.models.AwsCredentialsResponse
import java.io.File

class AWSS3Client(
   private val context: Context,
   private val awsFileUploadStatusListener: AWSFileUploadStatusListener
) {
   private val TAG = "AWSS3Client"
   fun uploadFile(file: File, awsCredentialsResponse: AwsCredentialsResponse, bucket:String) {
       startReadingAndUploading(file, awsCredentialsResponse,bucket)
   }

   private fun startReadingAndUploading(
       file: File,
       awsCredentialsResponse: AwsCredentialsResponse,
       bucket: String
   ) {
       val awsCredentials = BasicAWSCredentials(
           awsCredentialsResponse.awsAccessKey, awsCredentialsResponse.awsSecretKey
       )
       val s3Client = AmazonS3Client(awsCredentials, Region.getRegion(Regions.US_EAST_1))
       val transferUtility: TransferUtility = TransferUtility.builder()
           .context(context)
           .s3Client(s3Client)
           .build()
       TransferNetworkLossHandler.getInstance(context)
       val transferObserver: TransferObserver = transferUtility.upload(
           bucket,
           file.name,
           file,
           CannedAccessControlList.PublicReadWrite
       )
       transferObserver.setTransferListener(object : TransferListener {
           override fun onStateChanged(id: Int, state: TransferState) {
               Log.e(TAG, "onStateChanged : $id $state")
               if (state === TransferState.COMPLETED) {
                   val url = s3Client.getUrl(bucket, file.name)
                   awsFileUploadStatusListener.fileUploadCompleted(url.toString())
                   Log.e(TAG, "onStateChanged  url: $url")
               } else if (state === TransferState.CANCELED) {

               }
           }

           override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) {
               val percentDoneF = bytesCurrent.toFloat() / bytesTotal.toFloat() * 100
               val percentDone = percentDoneF.toInt()

               Log.e(TAG, "onProgressChanged :  $percentDone")

           }

           override fun onError(id: Int, exception: Exception) {
               Log.e(TAG, "onError : " + id + " " + exception.localizedMessage)
               awsFileUploadStatusListener.fileUploadError()
           }
       })
   }

   interface AWSFileUploadStatusListener {
       fun fileUploadCompleted(url: String)
       fun fileUploadError()
   }
}

Note: I have created a simple listener for the callback of complete and failure result so we can implement and get back the response in the same view

You can use this class like below:

//Simple AWS credential class to store keys

class AwsCredentialsResponse {
var awsAccessKey:String="your access key"
var awsSecretKey:String="your secret key"
}

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.urgidoctor.BuildConfig
import com.urgidoctor.R
import com.urgidoctor.databinding.ActivityCreateProfileStepsBinding
import com.urgidoctor.models.AwsCredentialsResponse
import com.urgidoctor.utils.*
import java.io.File

class CreateProfileStepsActivity : AppCompatActivity(),
   AWSS3Client.AWSFileUploadStatusListener{

   private val fileObject: File

   lateinit var createProfileStepsBinding: ActivityCreateProfileStepsBinding

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       createProfileStepsBinding =
           DataBindingUtil.setContentView(this, R.layout.activity_create_profile_steps)

       uploadProfilePicOnAWS(fileObject)
   }

   private fun uploadProfilePicOnAWS(file: File) {

       AWSS3Client(this, this).uploadFile(
           file,
           AwsCredentialsResponse(),
          “Your bucket”
       )

   }
  
   override fun fileUploadCompleted(url: String) {
       // you will get the se server file url here
   }

   override fun fileUploadError() {
       // handle failure case
   }

}

Note: Please save your credentials somewhere when you are creating a new account or IAM user on AWS because you’ll not get a secret key in the future from the console.

Conclusion

In this article, you learned about file uploading on the AWS server. If you have any questions feel free to ask in the comments section.

Krupa

Tech Expert

A forward-thinking developer with skills like designing, building integrating, testing, and supporting android mobile applications. Also known for writing efficient, maintainable and reusable code.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks