Skip to content

Instantly share code, notes, and snippets.

@bewithdhanu
Created January 11, 2023 13:42
Show Gist options
  • Save bewithdhanu/e6010019db832eaa44088f90dc8bd2d5 to your computer and use it in GitHub Desktop.
Save bewithdhanu/e6010019db832eaa44088f90dc8bd2d5 to your computer and use it in GitHub Desktop.
S3 File upload Kotlin using Amazon STS temporary credentials
private fun doFileTransfer(file: File) {

        val mCredentials = BasicSessionCredentials(YOUR_ACCESS_KEY, YOUR_SECRET_KEY, YOUR_SECRET_TOKEN)
        val s3: AmazonS3 = AmazonS3Client(mCredentials)
        s3.setRegion(Region.getRegion(Regions.US_EAST_2))
        mTransferUtility = TransferUtility.builder().s3Client(s3).context(mApplication).build()
        val objectKey = "android/${file.nameWithoutExtension}.${file.extension}";
        val access = CannedAccessControlList.Private

        val observer: TransferObserver = mTransferUtility.upload(YOUR_BUCKET, objectKey, file, access)
        Log.d("TAG ", "Trying to upload : $objectKey")
        observer.setTransferListener(object : TransferListener {
            override fun onStateChanged(id: Int, state: TransferState) {
                if (state == TransferState.COMPLETED) {
                    Log.d(TAG, "Uploaded to $objectKey")
                }
            }

            override fun onProgressChanged(id: Int, bytesCurrent: Long, bytesTotal: Long) {
                val percentage = (bytesCurrent / bytesTotal * 100).toInt()
                Log.e(TAG, "onProgressChanged() >> Uploading... $percentage %")
            }

            override fun onError(id: Int, ex: Exception) {
                ex.printStackTrace()
            }
        })
    }

    fun uploadFile(fileUri: Uri) {
        viewModelScope.launch(Dispatchers.IO) {


            val file = getFile(fileUri) ?: return@launch
            doFileTransfer(file)

        }
    }

    private fun getFile(fileUri: Uri): File? {

        try {
            val inputStream: InputStream? =
                mApplication.contentResolver.openInputStream(fileUri!!) //to read a file from content path

            val file = File.createTempFile(fileUri.toFile().nameWithoutExtension, ".${fileUri.toFile().extension}")

            val outStream: OutputStream =
                FileOutputStream(file)//creating stream pipeline to the file

            outStream.write(inputStream!!.readBytes())//passing bytes of data to the filestream / Write array of byte to current output stream

            outStream.close()
            return file
        } catch (ex: IOException) {
            return null
        } catch (ex: Exception) {
            return null
        }

    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment