https://kotlinlang.org logo
#ktor
Title
# ktor
j

Joey

03/25/2022, 2:12 PM
On a KMM project I'm uploading a large video from an Android device, but for some reason I get OutOfMemory exceptions even though, as far as I know, I'm streaming the file. Isn't this the right way to stream a binary file to a server? (thread for code)
Uploading
Copy code
withContext(<http://platformDispatchers.IO|platformDispatchers.IO>) {
    client.put<Unit>(urlString = uploadUrl) {
        body = StreamContent(File(fileInfo))
    }
}
The StreamContent class
Copy code
private class StreamContent(
    val file: File,
    override val contentType: ContentType = ContentType.Application.OctetStream,
) : OutgoingContent.WriteChannelContent() {
    override suspend fun writeTo(channel: ByteWriteChannel) {
        channel.bufferedWriter().use { output ->
            file.bufferedReader().use { input ->
                input.copyTo(output)
            }
        }
    }

    override val contentLength: Long = file.length()
}
d

David Nedrow

03/25/2022, 4:15 PM
Maybe
file.bufferedReader()
attempts to load the whole file in local memory? I'm not entirely sure how BufferedReader works in that regard, and the docs aren't clear.
24 Views