Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private fun uploadFileToS3Bucket(filePath: String, credential: AwsCredentialResponse): Maybe<String> {
- // from blog: http://blog.mallow-tech.com/2019/01/how-to-upload-files-from-an-android-app-to-aws-s3/
- return Maybe.create { emitter ->
- TransferNetworkLossHandler.getInstance(context)
- val simpleDateFormat = SimpleDateFormat(DateUtils.FORMAT_UTC, Locale.ENGLISH)
- val expirationDate = try {
- simpleDateFormat.parse(credential.credentials.expiration)
- } catch (e: Exception) {
- val calendar = Calendar.getInstance()
- calendar.add(Calendar.MINUTE, 10) // expiration time is 10 minutes from now
- Date(calendar.timeInMillis)
- }
- val s3Client: AmazonS3 =
- AmazonS3Client(
- AwsCredential(
- credential.credentials.accessKeyId,
- credential.credentials.accessKeyId,
- credential.credentials.sessionToken,
- expirationDate
- ),
- getRegion(Regions.EU_WEST_1)
- )
- val file = File(filePath)
- val transferUtility =
- TransferUtility.builder().s3Client(s3Client).context(context).build()
- val transferObserver: TransferObserver = transferUtility.upload(
- credential.bucket,
- credential.keyPrefix,
- file,
- CannedAccessControlList.PublicRead
- )
- transferObserver.setTransferListener(object : TransferListener {
- override fun onStateChanged(id: Int, state: TransferState?) {
- when (state) {
- TransferState.IN_PROGRESS -> {
- }
- TransferState.COMPLETED -> {
- }
- TransferState.FAILED -> {
- }
- else -> {
- }
- }
- }
- override fun onProgressChanged(
- id: Int,
- bytesCurrent: Long,
- bytesTotal: Long
- ) {
- if (bytesCurrent == bytesTotal) {
- emitter.onSuccess("${credential.bucket}/${credential.keyPrefix}/${file.name}")
- }
- }
- override fun onError(id: Int, e: Exception) {
- emitter.onError(e)
- }
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement