问题
I want to develop a simple android app to upload an image file to an already created S3 bucket in AWS. If I google, All the latest AWS documentations are redirecting me to use Amplify framework. I don't understand the documentation of uploading a file described here. I don't understand where I can provide bucket name, IAM credentials, etc. I don't find any video tutorials as well. Why AWS if forcing to use Amplify without providing proper documentation?
Here they mention to configure all details in Amplify CLI using
amplify add storage
And ask to push changes using
amplify push
But if we want to add details such as bucket name, user details, etc. programmatically, then how do we do it? Give me step by step details either using Amplify framework or old AWS SDK for android for uploading file without Cognito
回答1:
There are a number of ways to upload files to S3, from an Android device. Here are a few.
Using Amplify Android
The main documentation for Amplify Android's Storage category is written with the assumption that you'll create new AWS resources, using the Amplify CLI. There are also some note about using an existing S3 bucket.
Using the AWS SDK for Android
If neither meet your needs, you can use the old TransferUtility
from the AWS SDK for Android. Here's an example use of the TransferUtility.
AWS SDK for Android, No Cognito
As you note, the documentation above uses the AWSMobileClient
, which is an interface to Amazon Cognito. However, you can use any implementation of the CredentialsProvider
, for authentication; AWSMobileClient
is just one example of a credentials provider.
The simplest (and a least secure) approach might be to provide an IAM user's access and secret key using a StaticCredentialsProvider
, as below.
val region = Region.getRegion(Regions.US_EAST_1)
val credentials = BasicAWSCredentials(accessKey, secretKey)
val provider = StaticCredentialsProvider(credentials)
val transferUtility = TransferUtility.builder()
.context(applicationContext)
.s3Client(AmazonS3Client(provider, region))
.awsConfiguration(AWSConfiguration(applicationContext))
.build()
val listener = object: TransferListener {
override fun onProgressChanged(id: Int, curr: Long, tot: Long) {}
override fun onStateChanged(id: Int, state: TransferState?) {
when (state) {
COMPLETED -> { Log.i("Demo", "Upload succeeded.") }
FAILED -> { /* handle err */ }
else -> { /* handle cases... */ }
}
}
override fun onError(id: Int, ex: Exception?) { /* handle err */ }
}
transferUtility.upload(remoteBucket, remoteKey, localFile)
.setTransferListener(listener)
来源:https://stackoverflow.com/questions/62973171/android-amplify-uploading-downloading-file-to-from-aws-s3-using-amplify