Created
June 4, 2020 09:09
-
-
Save meetjanani-simformsolutions/a2c6c6ba5636a05036a2d143d3b8fd18 to your computer and use it in GitHub Desktop.
AWS Upload Image on S3 Using Cognito Pool ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| single { | |
| ClientConfiguration().apply { | |
| maxErrorRetry = 3 | |
| connectionTimeout = 5 * 1000 | |
| socketTimeout = 5 * 1000 | |
| protocol = Protocol.HTTP | |
| } | |
| } | |
| single { | |
| val cognitoCachingCredentialsProvider = CognitoCachingCredentialsProvider(androidContext(), BuildConfig.COGNITO_POOL_ID, Regions.US_EAST_1) | |
| val s3Client = AmazonS3Client(cognitoCachingCredentialsProvider, Region.getRegion(Regions.US_EAST_1), get()) | |
| s3Client.endpoint = BuildConfig.AWS_END_POINT | |
| val builder = S3ClientOptions.builder().setPathStyleAccess(true).build() | |
| s3Client.setS3ClientOptions(builder) | |
| s3Client.setRegion(Region.getRegion(Regions.US_EAST_1)) | |
| s3Client | |
| } | |
| single { | |
| TransferUtility.builder() | |
| .context(androidContext()) | |
| .s3Client(get()) | |
| .defaultBucket(BuildConfig.BUCKET_NAME) | |
| .build() | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Dependancy | |
| com.amazonaws:aws-android-sdk-s3:2.16.6 | |
| Details that we required from AWS Console | |
| 1) Bucket_Name | |
| 2) Cognito_Pool_ID | |
| 3) Aws_End_Point = Bucket_Name + s3.amazonaws.com |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * This fun is used to upload image in S3 with dynamic bucket. | |
| * @receiver Activity | |
| * @param uriPath String | |
| * @param fileName String | |
| */ | |
| fun Activity.uploadImageInS3(file: File, fileName : String, directoryPath: String): ImageUploadUtils.ImageUploadListener { | |
| val listener = ImageUploadUtils.ImageUploadListener() | |
| uploadImage(file, fileName, listener, directoryPath) | |
| return listener | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private fun uploadImage(){ | |
| viewModel.isApiLoading(true) | |
| var file = File(imageFilePath) | |
| uploadImageInS3(file, "${userPref.data.user?.id}.${file.extension}", userProfilePicture).onProgress { | |
| }.onSuccess() { url: String, directory: String, fileName: String -> | |
| state.editProfileRequest.value?.profileImage = "${BuildConfig.AWS_BASE_URL}$directory/$fileName" | |
| imageViewUserProfile.loadImage( "${BuildConfig.AWS_BASE_URL}$directory/$fileName", true){} | |
| showSuccess(getString(R.string.str_image_selected)) | |
| viewModel.isApiLoading(false) | |
| state.isProfilePictureChangeByUser.postValue(true) | |
| imageFilePath = "" | |
| }.onFailure { | |
| showError(it) | |
| viewModel.isApiLoading(false) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.mediacentric.app.utils | |
| import android.content.Context | |
| import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener | |
| import com.amazonaws.mobileconnectors.s3.transferutility.TransferState | |
| import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility | |
| import com.amazonaws.services.s3.AmazonS3Client | |
| import com.amazonaws.services.s3.model.CannedAccessControlList | |
| import com.mediacentric.app.BuildConfig | |
| import com.mediacentric.app.R | |
| import com.mediacentric.app.extension.hasConnection | |
| import org.koin.core.KoinComponent | |
| import org.koin.core.inject | |
| import timber.log.Timber | |
| import java.io.File | |
| /** | |
| * This class is used to upload image. | |
| */ | |
| object ImageUploadUtils : KoinComponent { | |
| private val amazonS3Client: AmazonS3Client by inject() | |
| private const val PROGRESSPERCENTAGE = 100 | |
| /** upload Image on aws */ | |
| fun Context.uploadImage(file: File, fileName: String, listener: ImageUploadListener, directoryPath: String) { | |
| runCatching { | |
| val transferUtility = TransferUtility.builder() | |
| .context(this) | |
| .s3Client(amazonS3Client) | |
| .defaultBucket(BuildConfig.BUCKET_NAME) | |
| .build() | |
| if (file.length() > 0) { | |
| val venueBucket = "${BuildConfig.BUCKET_NAME}/$directoryPath" | |
| var previousId = 0 | |
| val observer = transferUtility.upload(venueBucket, fileName, file, CannedAccessControlList.PublicReadWrite) | |
| observer?.setTransferListener(object : TransferListener { | |
| override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) { | |
| var percentage = 0 | |
| if (bytesTotal != 0L) { | |
| percentage = (bytesCurrent * PROGRESSPERCENTAGE / bytesTotal).toInt() | |
| if (percentage == PROGRESSPERCENTAGE) { | |
| if (previousId != id) { | |
| listener.onSuccessFunc(amazonS3Client.getUrl(venueBucket, fileName).toString(), directoryPath, fileName) | |
| previousId = id | |
| } | |
| } else { | |
| listener.onProgressFunc(percentage) | |
| } | |
| } else { | |
| listener.onProgressFunc(percentage) | |
| } | |
| } | |
| override fun onStateChanged(id: Int, state: TransferState?) { | |
| if (!hasConnection()) | |
| listener.onFailureFunc(getString(R.string.msg_no_internet)) | |
| } | |
| override fun onError(id: Int, ex: Exception?) { | |
| uploadFail(this@uploadImage, ex?.localizedMessage, listener) | |
| } | |
| }) | |
| } else { | |
| listener.onFailureFunc("Please choose image.") | |
| } | |
| }.onFailure { | |
| uploadFail(this, it.localizedMessage, listener) | |
| } | |
| } | |
| /** | |
| * image upload fail | |
| */ | |
| fun uploadFail(context: Context, message: String?, listener: ImageUploadListener) { | |
| if (message != null) { | |
| listener.onFailureFunc(message) | |
| } else { | |
| listener.onFailureFunc("Unknown Error") | |
| } | |
| } | |
| /** | |
| * image upload listener | |
| */ | |
| class ImageUploadListener { | |
| var onProgressFunc: (Int) -> Unit = {} | |
| var onSuccessFunc: (String, String, String) -> Unit = { url: String, directory: String, fileName: String -> } | |
| var onFailureFunc: (String) -> Unit = {} | |
| /** upload image progress */ | |
| fun onProgress(func: (Int) -> Unit) = apply { | |
| this.onProgressFunc = func | |
| } | |
| /** upload image completed */ | |
| fun onSuccess(func: (String, String, String) -> Unit) = apply { | |
| this.onSuccessFunc = func | |
| } | |
| /** upload image failure */ | |
| fun onFailure(func: (String) -> Unit) = apply { | |
| this.onFailureFunc = func | |
| Timber.d(func.toString()) | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AWS Upload Image on S3 Using Cognito Pool ID