用SDK于 Kotlin 的 Amazon S3 示例 - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

用SDK于 Kotlin 的 Amazon S3 示例

以下代码示例向您展示了如何在 Amazon S3 中使用 for Kotlin 来执行操作和实现常见场景。 AWS SDK

基础知识是向您展示如何在服务中执行基本操作的代码示例。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。

场景是向您展示如何通过在一个服务中调用多个函数或与其他 AWS 服务结合来完成特定任务的代码示例。

每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

基础知识

以下代码示例展示了如何:

  • 创建桶并将文件上载到其中。

  • 从桶中下载对象。

  • 将对象复制到存储桶中的子文件夹。

  • 列出存储桶中的对象。

  • 删除存储桶及其对象。

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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!") } }

操作

以下代码示例显示了如何使用CopyObject

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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) } }
  • 有关API详细信息,请参阅CopyObject中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用CreateBucket

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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") } }
  • 有关API详细信息,请参阅CreateBucket中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用CreateMultiRegionAccessPoint

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

将 S3 控制客户端配置为向 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 }

创建多区域接入点。

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" }

等待多区域接入点变为可用状态。

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) } }

以下代码示例显示了如何使用DeleteBucketPolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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

以下代码示例显示了如何使用DeleteObjects

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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") } }
  • 有关API详细信息,请参阅DeleteObjects中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用GetBucketPolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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 } }
  • 有关API详细信息,请参阅GetBucketPolicy中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用GetObject

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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") } } }
  • 有关API详细信息,请参阅GetObject中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用GetObjectAcl

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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}") } } }
  • 有关API详细信息,请参阅GetObjectAcl中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用ListObjectsV2

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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
  • 有关API详细信息,请参阅中的 ListObjectsV2 以获取 Kotlin AWS SDK 参考API

以下代码示例显示了如何使用PutBucketAcl

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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") } }
  • 有关API详细信息,请参阅PutBucketAcl中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用PutObject

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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}") } }
  • 有关API详细信息,请参阅PutObject中的 Kotlin AWS SDK API 参考

场景

以下代码示例演示如何为 Amazon S3 创建URL预签名文件并上传对象。

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

创建GetObject预签名请求URL并使用下载对象。

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 }

使用高级选项创建 GetObject 预签名请求。

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 }

创建 PutObject 预签名请求并使用它上传对象。

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) }

以下代码示例演示如何创建无服务器应用程序,让用户能够使用标签管理照片。

SDK对于 Kotlin 来说

演示如何开发照片资产管理应用程序,该应用程序使用 Amazon Rekognition 检测图像中的标签并将其存储以供日后检索。

有关如何设置和运行的完整源代码和说明,请参阅上的完整示例 GitHub

要深入了解这个例子的起源,请参阅 AWS 社区上的博文。

本示例中使用的服务
  • API网关

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

以下代码示例演示如何构建一个使用 Amazon Rekognition 按类别检测图像中对象的应用程序。

SDK对于 Kotlin 来说

演示如何使用 Amazon API Rekognition Kotlin 创建一款应用程序,该应用程序使用 Amazon Rekognition 按类别识别位于亚马逊简单存储服务 (Amazon S3) 存储桶中的图像中的对象。该应用程序使用亚马逊简单电子邮件服务 (AmazonSES) 向管理员发送一封包含结果的电子邮件通知。

有关如何设置和运行的完整源代码和说明,请参阅上的完整示例GitHub

本示例中使用的服务
  • Amazon Rekognition

  • Amazon S3

  • Amazon SES

以下代码示例显示如何从多区域接入点中获取对象。

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

将 S3 客户端配置为使用非对称 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 }

使用多区域接入点ARN而不是存储桶名称来检索对象。

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 }