Exemplos do Amazon S3 usando SDK para Kotlin - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Exemplos do Amazon S3 usando SDK para Kotlin

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK for Kotlin com o Amazon S3.

As noções básicas são exemplos de código que mostram como realizar as operações essenciais em um serviço.

Ações são trechos de código de programas maiores e devem ser executadas em contexto. Embora as ações mostrem como chamar funções de serviço individuais, você pode ver as ações no contexto em seus cenários relacionados.

Os cenários são exemplos de código que mostram como realizar tarefas específicas chamando várias funções dentro de um serviço ou combinadas com outros Serviços da AWS.

Cada exemplo inclui um link para o código-fonte completo, onde você pode encontrar instruções sobre como configurar e executar o código no contexto.

Conceitos básicos

O exemplo de código a seguir mostra como:

  • Criar um bucket e fazer upload de um arquivo para ele.

  • Baixar um objeto de um bucket.

  • Copiar um objeto em uma subpasta em um bucket.

  • Listar os objetos em um bucket.

  • Excluir os objetos do bucket e o bucket.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun main(args: Array<String>) { val usage = """ Usage: <bucketName> <key> <objectPath> <savePath> <toBucket> Where: bucketName - The Amazon S3 bucket to create. key - The key to use. objectPath - The path where the file is located (for example, C:/AWS/book2.pdf). savePath - The path where the file is saved after it's downloaded (for example, C:/AWS/book2.pdf). toBucket - An Amazon S3 bucket to where an object is copied to (for example, C:/AWS/book2.pdf). """ if (args.size != 4) { println(usage) exitProcess(1) } val bucketName = args[0] val key = args[1] val objectPath = args[2] val savePath = args[3] val toBucket = args[4] // Create an Amazon S3 bucket. createBucket(bucketName) // Update a local file to the Amazon S3 bucket. putObject(bucketName, key, objectPath) // Download the object to another local file. getObjectFromMrap(bucketName, key, savePath) // List all objects located in the Amazon S3 bucket. listBucketObs(bucketName) // Copy the object to another Amazon S3 bucket copyBucketOb(bucketName, key, toBucket) // Delete the object from the Amazon S3 bucket. deleteBucketObs(bucketName, key) // Delete the Amazon S3 bucket. deleteBucket(bucketName) println("All Amazon S3 operations were successfully performed") } suspend fun createBucket(bucketName: String) { val request = CreateBucketRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.createBucket(request) println("$bucketName is ready") } } suspend fun putObject( bucketName: String, objectKey: String, objectPath: String, ) { val metadataVal = mutableMapOf<String, String>() metadataVal["myVal"] = "test" val request = PutObjectRequest { bucket = bucketName key = objectKey metadata = metadataVal this.body = Paths.get(objectPath).asByteStream() } S3Client { region = "us-east-1" }.use { s3 -> val response = s3.putObject(request) println("Tag information is ${response.eTag}") } } suspend fun getObjectFromMrap( bucketName: String, keyName: String, path: String, ) { val request = GetObjectRequest { key = keyName bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.getObject(request) { resp -> val myFile = File(path) resp.body?.writeToFile(myFile) println("Successfully read $keyName from $bucketName") } } } suspend fun listBucketObs(bucketName: String) { val request = ListObjectsRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> val response = s3.listObjects(request) response.contents?.forEach { myObject -> println("The name of the key is ${myObject.key}") println("The owner is ${myObject.owner}") } } } suspend fun copyBucketOb( fromBucket: String, objectKey: String, toBucket: String, ) { var encodedUrl = "" try { encodedUrl = URLEncoder.encode("$fromBucket/$objectKey", StandardCharsets.UTF_8.toString()) } catch (e: UnsupportedEncodingException) { println("URL could not be encoded: " + e.message) } val request = CopyObjectRequest { copySource = encodedUrl bucket = toBucket key = objectKey } S3Client { region = "us-east-1" }.use { s3 -> s3.copyObject(request) } } suspend fun deleteBucketObs( bucketName: String, objectName: String, ) { val objectId = ObjectIdentifier { key = objectName } val delOb = Delete { objects = listOf(objectId) } val request = DeleteObjectsRequest { bucket = bucketName delete = delOb } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteObjects(request) println("$objectName was deleted from $bucketName") } } suspend fun deleteBucket(bucketName: String?) { val request = DeleteBucketRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteBucket(request) println("The $bucketName was successfully deleted!") } }

Ações

O código de exemplo a seguir mostra como usar CopyObject.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun copyBucketObject( fromBucket: String, objectKey: String, toBucket: String, ) { var encodedUrl = "" try { encodedUrl = URLEncoder.encode("$fromBucket/$objectKey", StandardCharsets.UTF_8.toString()) } catch (e: UnsupportedEncodingException) { println("URL could not be encoded: " + e.message) } val request = CopyObjectRequest { copySource = encodedUrl bucket = toBucket key = objectKey } S3Client { region = "us-east-1" }.use { s3 -> s3.copyObject(request) } }
  • Para API obter detalhes, consulte a CopyObjectreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar CreateBucket.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun createNewBucket(bucketName: String) { val request = CreateBucketRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.createBucket(request) println("$bucketName is ready") } }
  • Para API obter detalhes, consulte a CreateBucketreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar CreateMultiRegionAccessPoint.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Configure o cliente de controle do S3 para enviar a solicitação à região us-west-2.

suspend fun createS3ControlClient(): S3ControlClient { // Configure your S3ControlClient to send requests to US West (Oregon). val s3Control = S3ControlClient.fromEnvironment { region = "us-west-2" } return s3Control }

Crie o ponto de acesso multirregional.

suspend fun createMrap( s3Control: S3ControlClient, accountIdParam: String, bucketName1: String, bucketName2: String, mrapName: String, ): String { println("Creating MRAP ...") val createMrapResponse: CreateMultiRegionAccessPointResponse = s3Control.createMultiRegionAccessPoint { accountId = accountIdParam clientToken = UUID.randomUUID().toString() details { name = mrapName regions = listOf( Region { bucket = bucketName1 }, Region { bucket = bucketName2 }, ) } } val requestToken: String? = createMrapResponse.requestTokenArn // Use the request token to check for the status of the CreateMultiRegionAccessPoint operation. if (requestToken != null) { waitForSucceededStatus(s3Control, requestToken, accountIdParam) println("MRAP created") } val getMrapResponse = s3Control.getMultiRegionAccessPoint( input = GetMultiRegionAccessPointRequest { accountId = accountIdParam name = mrapName }, ) val mrapAlias = getMrapResponse.accessPoint?.alias return "arn:aws:s3::$accountIdParam:accesspoint/$mrapAlias" }

Aguarde até que o ponto de acesso multirregional fique disponível.

suspend fun waitForSucceededStatus( s3Control: S3ControlClient, requestToken: String, accountIdParam: String, timeBetweenChecks: Duration = 1.minutes, ) { var describeResponse: DescribeMultiRegionAccessPointOperationResponse describeResponse = s3Control.describeMultiRegionAccessPointOperation( input = DescribeMultiRegionAccessPointOperationRequest { accountId = accountIdParam requestTokenArn = requestToken }, ) var status: String? = describeResponse.asyncOperation?.requestStatus while (status != "SUCCEEDED") { delay(timeBetweenChecks) describeResponse = s3Control.describeMultiRegionAccessPointOperation( input = DescribeMultiRegionAccessPointOperationRequest { accountId = accountIdParam requestTokenArn = requestToken }, ) status = describeResponse.asyncOperation?.requestStatus println(status) } }

O código de exemplo a seguir mostra como usar DeleteBucketPolicy.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun deleteS3BucketPolicy(bucketName: String?) { val request = DeleteBucketPolicyRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteBucketPolicy(request) println("Done!") } }

O código de exemplo a seguir mostra como usar DeleteObjects.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun deleteBucketObjects( bucketName: String, objectName: String, ) { val objectId = ObjectIdentifier { key = objectName } val delOb = Delete { objects = listOf(objectId) } val request = DeleteObjectsRequest { bucket = bucketName delete = delOb } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteObjects(request) println("$objectName was deleted from $bucketName") } }
  • Para API obter detalhes, consulte a DeleteObjectsreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar GetBucketPolicy.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun getPolicy(bucketName: String): String? { println("Getting policy for bucket $bucketName") val request = GetBucketPolicyRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> val policyRes = s3.getBucketPolicy(request) return policyRes.policy } }
  • Para API obter detalhes, consulte a GetBucketPolicyreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar GetObject.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun getObjectBytes( bucketName: String, keyName: String, path: String, ) { val request = GetObjectRequest { key = keyName bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.getObject(request) { resp -> val myFile = File(path) resp.body?.writeToFile(myFile) println("Successfully read $keyName from $bucketName") } } }
  • Para API obter detalhes, consulte a GetObjectreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar GetObjectAcl.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun getBucketACL( objectKey: String, bucketName: String, ) { val request = GetObjectAclRequest { bucket = bucketName key = objectKey } S3Client { region = "us-east-1" }.use { s3 -> val response = s3.getObjectAcl(request) response.grants?.forEach { grant -> println("Grant permission is ${grant.permission}") } } }
  • Para API obter detalhes, consulte a GetObjectAclreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar ListObjectsV2.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun listBucketObjects(bucketName: String) { val request = ListObjectsRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> val response = s3.listObjects(request) response.contents?.forEach { myObject -> println("The name of the key is ${myObject.key}") println("The object is ${myObject.size?.let { calKb(it) }} KBs") println("The owner is ${myObject.owner}") } } } private fun calKb(intValue: Long): Long = intValue / 1024
  • Para API obter detalhes, consulte ListObjectsV2 em AWS SDKpara referência ao Kotlin API.

O código de exemplo a seguir mostra como usar PutBucketAcl.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun setBucketAcl( bucketName: String, idVal: String, ) { val myGrant = Grantee { id = idVal type = Type.CanonicalUser } val ownerGrant = Grant { grantee = myGrant permission = Permission.FullControl } val grantList = mutableListOf<Grant>() grantList.add(ownerGrant) val ownerOb = Owner { id = idVal } val acl = AccessControlPolicy { owner = ownerOb grants = grantList } val request = PutBucketAclRequest { bucket = bucketName accessControlPolicy = acl } S3Client { region = "us-east-1" }.use { s3 -> s3.putBucketAcl(request) println("An ACL was successfully set on $bucketName") } }
  • Para API obter detalhes, consulte a PutBucketAclreferência AWS SDKdo Kotlin API.

O código de exemplo a seguir mostra como usar PutObject.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

suspend fun putS3Object( bucketName: String, objectKey: String, objectPath: String, ) { val metadataVal = mutableMapOf<String, String>() metadataVal["myVal"] = "test" val request = PutObjectRequest { bucket = bucketName key = objectKey metadata = metadataVal body = File(objectPath).asByteStream() } S3Client { region = "us-east-1" }.use { s3 -> val response = s3.putObject(request) println("Tag information is ${response.eTag}") } }
  • Para API obter detalhes, consulte a PutObjectreferência AWS SDKdo Kotlin API.

Cenários

O exemplo de código a seguir mostra como criar um pré-assinado URL para o Amazon S3 e fazer o upload de um objeto.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Crie uma solicitação GetObject pré-assinada e use-a URL para baixar um objeto.

suspend fun getObjectPresigned( s3: S3Client, bucketName: String, keyName: String, ): String { // Create a GetObjectRequest. val unsignedRequest = GetObjectRequest { bucket = bucketName key = keyName } // Presign the GetObject request. val presignedRequest = s3.presignGetObject(unsignedRequest, 24.hours) // Use the URL from the presigned HttpRequest in a subsequent HTTP GET request to retrieve the object. val objectContents = URL(presignedRequest.url.toString()).readText() return objectContents }

Crie uma solicitação GetObject atribuída previamente com opções avançadas.

suspend fun getObjectPresignedMoreOptions( s3: S3Client, bucketName: String, keyName: String, ): HttpRequest { // Create a GetObjectRequest. val unsignedRequest = GetObjectRequest { bucket = bucketName key = keyName } // Presign the GetObject request. val presignedRequest = s3.presignGetObject(unsignedRequest, signer = CrtAwsSigner) { signingDate = Instant.now() + 12.hours // Presigned request can be used 12 hours from now. algorithm = AwsSigningAlgorithm.SIGV4_ASYMMETRIC signatureType = AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS expiresAfter = 8.hours // Presigned request expires 8 hours later. } return presignedRequest }

Crie uma solicitação pré-assinada de PutObject e use-a para fazer upload de um objeto.

suspend fun putObjectPresigned( s3: S3Client, bucketName: String, keyName: String, content: String, ) { // Create a PutObjectRequest. val unsignedRequest = PutObjectRequest { bucket = bucketName key = keyName } // Presign the request. val presignedRequest = s3.presignPutObject(unsignedRequest, 24.hours) // Use the URL and any headers from the presigned HttpRequest in a subsequent HTTP PUT request to retrieve the object. // Create a PUT request using the OKHttpClient API. val putRequest = Request .Builder() .url(presignedRequest.url.toString()) .apply { presignedRequest.headers.forEach { key, values -> header(key, values.joinToString(", ")) } }.put(content.toRequestBody()) .build() val response = OkHttpClient().newCall(putRequest).execute() assert(response.isSuccessful) }

O exemplo de código a seguir mostra como criar uma aplicação com tecnologia sem servidor que permite que os usuários gerenciem fotos usando rótulos.

SDKpara Kotlin

Mostra como desenvolver uma aplicação de gerenciamento de ativos fotográficos que detecta rótulos em imagens usando o Amazon Rekognition e os armazena para recuperação posterior.

Para obter o código-fonte completo e instruções sobre como configurar e executar, veja o exemplo completo em GitHub.

Para uma análise detalhada da origem desse exemplo, veja a publicação na Comunidade da AWS.

Serviços utilizados neste exemplo
  • APIGateway

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

O exemplo de código a seguir mostra como criar um aplicativo que usa o Amazon Rekognition para detectar objetos por categoria em imagens.

SDKpara Kotlin

Mostra como usar o Amazon Rekognition API Kotlin para criar um aplicativo que usa o Amazon Rekognition para identificar objetos por categoria em imagens localizadas em um bucket do Amazon Simple Storage Service (Amazon S3). O aplicativo envia ao administrador uma notificação por e-mail com os resultados usando o Amazon Simple Email Service (AmazonSES).

Para obter o código-fonte completo e instruções sobre como configurar e executar, veja o exemplo completo em GitHub.

Serviços utilizados neste exemplo
  • Amazon Rekognition

  • Amazon S3

  • Amazon SES

O exemplo de código a seguir demonstra como obter um objeto de um ponto de acesso multirregional.

SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Configure o cliente do S3 para usar o algoritmo de assinatura Asymmetric Sigv4 (Sigv4a).

suspend fun createS3Client(): S3Client { // Configure your S3Client to use the Asymmetric Sigv4 (Sigv4a) signing algorithm. val sigV4AScheme = SigV4AsymmetricAuthScheme(CrtAwsSigner) val s3 = S3Client.fromEnvironment { authSchemes = listOf(sigV4AScheme) } return s3 }

Use o ponto de acesso multirregional ARN em vez do nome de um bucket para recuperar o objeto.

suspend fun getObjectFromMrap( s3: S3Client, mrapArn: String, keyName: String, ): String? { val request = GetObjectRequest { bucket = mrapArn // Use the ARN instead of the bucket name for object operations. key = keyName } var stringObj: String? = null s3.getObject(request) { resp -> stringObj = resp.body?.decodeToString() if (stringObj != null) { println("Successfully read $keyName from $mrapArn") } } return stringObj }
  • Para obter mais informações, consulte o guia AWS SDK do desenvolvedor do Kotlin.

  • Para API obter detalhes, consulte a GetObjectreferência AWS SDKdo Kotlin API.