Skip to content

Instantly share code, notes, and snippets.

@francescogatto
Created October 27, 2019 14:38
Show Gist options
  • Save francescogatto/648ad2c22f8094421d5cc712054cca50 to your computer and use it in GitHub Desktop.
Save francescogatto/648ad2c22f8094421d5cc712054cca50 to your computer and use it in GitHub Desktop.
#kkd
suspend fun HttpClient.downloadFile(file: File, url: String, callback: suspend (boolean: Boolean) -> Unit) {
val response = call {
url(url)
method = HttpMethod.Get
}.response
val data = ByteArray(response.contentLength()!!.toInt())
var offset = 0
do {
val currentRead = response.content.readAvailable(data, offset, data.size)
offset += currentRead
val progress = (offset.toFloat() * 100f / data.size.toFloat()).roundToInt()
} while (currentRead > 0)
response.close()
if (!response.status.isSuccess()) {
callback(false)
}
file.writeBytes(data)
callback(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment