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.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?