or better question, how would I download a large f...
# ktor
k
or better question, how would I download a large file with the ktor http client?
c
Copy code
client.get<HttpResponse>(...).use { response ->
    val channel = response.content
    ...
}
k
Thanks!
what's the best way to write to a file from a bytechannel?
This is the ultimate solution I ended up coming up with
Copy code
suspend fun downloadFile(url: String) = GlobalScope.produce {
    HttpClient().get<HttpResponse>(url).use { response ->
        val size = (response.headers["Content-Length"] ?: "-1").toInt()
        val buf = ByteBuffer.allocate(2048)
        FileOutputStream(File(DocSetStore.docSetStore, url.split("/").last())).use { out ->
            var totalRead = 0
            do {
                val readAmount = response.content.readAvailable(buf)
                if (readAmount != -1) {
                    totalRead += readAmount
                }

                buf.flip()
                out.channel.write(buf)
                buf.clear()

                send(
                        if (size == -1) {
                            -1L
                        } else {
                            (totalRead * 100L) / size
                        }
                )
            } while (readAmount > -1)
        }
    }
}