Hi, I’m using Ktor server and the Ktor client to a...
# ktor
m
Hi, I’m using Ktor server and the Ktor client to achieve the following. My API users request a file from my API. The Ktor client downloads this file and responds the file to the API user. While this works using this code:
Copy code
val fileChannel: ByteReadChannel = client.get("<https://example.com/bigfile.bin>").body()

call.response.header(
    HttpHeaders.ContentDisposition,
    ContentDisposition.Attachment.withParameter(
        ContentDisposition.Parameters.FileName,
        fileName
    ).toString()
)

call.respond(fileChannel)
the the Profiler shows that a large amount of memory is used by a
byte[]
. What do I miss here? Where is the
ByteReadChannel
converted into a byte array, and therefore read into memory?
a
The problem is that the
get
call reads the entire response body into memory. You can use the following code to stream the response body:
Copy code
client.prepareGet("<https://example.com/bigfile.bin>").execute { response -> 
    call.respond(response.bodyAsChannel())
}
✔️ 4