Wai Yan Hein
Wai Yan Hein

Reputation: 14831

Uploading file as public to S3 in Kotlin Android

I am developing an Android application using Kotlin. I am trying to upload file to the AWS S3 bucket. I could upload to the file to the Bucket successfully. But the problem is that the file is uploaded as private. Instead I want it to be uploaded and set public as well.

This is my code

private fun uploadPhotoToS3(path : String){
        doAsync {
            AWSMobileClient.getInstance().initialize(applicationContext).execute()

            val s3Client = AmazonS3Client(AWSMobileClient.getInstance().credentialsProvider)
            val transferUtility = TransferUtility.builder()
                    .context(applicationContext)
                    .awsConfiguration(AWSMobileClient.getInstance().configuration)
                    .s3Client(s3Client)
                    .build()
            val uploadObserver = transferUtility.upload("public/testing.jpg", File(path))

            uploadObserver.setTransferListener(object : TransferListener{
                override fun onStateChanged(id: Int, state: TransferState?) {
                    if(TransferState.COMPLETED == state){
                        Log.i("UPLOAD_STATE", "COMPLETED")
                    } else {
                        Log.i("UPLOAD_STATE", "CHANGED")
                    }
                }

                override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) {

                }

                override fun onError(id: Int, ex: Exception?) {
                    Log.i("UPLOAD_ERROR", "Unable to upload file")
                }
            })
        }
    }

How can I modify it to set the file to public?

Upvotes: 2

Views: 6039

Answers (3)

Ruby
Ruby

Reputation: 1441

Reference: https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-s3/src/main/java/com/amazonaws/mobileconnectors/s3/transferutility/TransferUtility.java#L476

val uploadObserver = transferUtility.upload("public/testing.jpg", File(path), CannedAccessControlList.PublicRead)

Additional

I tried the above solution. But it was returning 403 error. Instead of using cognito credentials provider, I had to use the AWS Basic Credentials Provider with the Access Key and the Secret Key.

Upvotes: 1

Julia Tsymbalyuk
Julia Tsymbalyuk

Reputation: 1

Regarding "Access Denied" error: try using aws-sdk-android-s3 2.7.3 instead of the latest 2.7.5. The issue is tracked here https://github.com/aws/aws-sdk-android/issues/548

Upvotes: 0

Related Questions