How to download file with ktor in kotlin

To download a file with ktor 2.0.0 in kotlin you can use the writeChannels kotlin utility. Channels allows you to pass data to each coroutines in a non-blocking fashion.

val outputFile = File(context.cacheDir, "yourFileName")

val out: ByteReadChannel = ktorClient.get {
  url("your url")
  method = HttpMethod.Get
}.bodyAsChannel()

out.copyAndClose(outputFile.writeChannel())

outputFile defines the file where to write the data

ktorClient is your ktor client

Other articles