

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 串流操作
<a name="streaming-ops"></a>

在 中 適用於 Kotlin 的 AWS SDK，二進位資料 （串流） 表示為[https://docs.aws.amazon.com/smithy-kotlin/api/latest/runtime-core/aws.smithy.kotlin.runtime.content/-byte-stream/index.html](https://docs.aws.amazon.com/smithy-kotlin/api/latest/runtime-core/aws.smithy.kotlin.runtime.content/-byte-stream/index.html)類型，這是抽象的唯讀位元組串流。

## 串流回應
<a name="streaming-responses"></a>

使用二進位串流 （例如 Amazon Simple Storage Service (Amazon S3) [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) API 操作） 的回應處理方式與其他方法不同。這些方法採用處理回應的 lambda 函數，而不是直接傳回回應。這會限制對 函數的回應範圍，並簡化呼叫者和 SDK 執行時間的生命週期管理。

在 lambda 函數傳回後，會釋出任何資源，例如基礎 HTTP 連線。(`ByteStream`不應在 Lambda 傳回後存取 ，也不應從關閉中移出。) 呼叫的結果是 lambda 傳回的任何內容。

下列程式碼範例顯示接收 lambda 參數的 [getObject](https://docs.aws.amazon.com/sdk-for-kotlin/api/latest/s3/aws.sdk.kotlin.services.s3/-s3-client/get-object.html) 函數，該參數會處理回應。

```
val s3Client = S3Client.fromEnvironment()
val req = GetObjectRequest { ... }

val path = Paths.get("/tmp/download.txt")

// S3Client.getObject has the following signature:
// suspend fun <T> getObject(input: GetObjectRequest, block: suspend (GetObjectResponse) -> T): T

val contentSize = s3Client.getObject(req) { resp ->
    // resp is valid until the end of the block.
    // Do not attempt to store or process the stream after the block returns.
    
    // resp.body is of type ByteStream.
    val rc = resp.body?.writeToFile(path)
    rc
}
println("wrote $contentSize bytes to $path")
```

對於常見的使用方式， `ByteStream`類型具有下列延伸：
+ `ByteStream.writeToFile(file: File): Long`
+ `ByteStream.writeToFile(path: Path): Long`
+ `ByteStream.toByteArray(): ByteArray`
+ `ByteStream.decodeToString(): String`

所有這些都是在 `aws.smithy.kotlin.runtime.content`套件中定義。

## 串流請求
<a name="streaming-requests"></a>

若要提供 `ByteStream`，也有數種便利方法，包括下列項目：
+ `ByteStream.fromFile(file: File)`
+ `File.asByteStream(): ByteStream`
+ `Path.asByteStream(): ByteStream`
+ `ByteStream.fromBytes(bytes: ByteArray)`
+ `ByteStream.fromString(str: String)`

所有這些都是在 `aws.smithy.kotlin.runtime.content`套件中定義。

下列程式碼範例顯示使用`ByteStream`便利方法，在建立 [PutObjectRequest](https://docs.aws.amazon.com/sdk-for-kotlin/api/latest/s3/aws.sdk.kotlin.services.s3.model/-put-object-request/index.html) 時提供內文屬性：

```
val req = PutObjectRequest {
    ...
    body = ByteStream.fromFile(file)
    // body = ByteStream.fromBytes(byteArray)
    // body = ByteStream.fromString("string")
    // etc
}
```