-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFileDownloader.kt
More file actions
45 lines (42 loc) · 1.48 KB
/
FileDownloader.kt
File metadata and controls
45 lines (42 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.nitrofs
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.onDownload
import io.ktor.client.request.prepareGet
import io.ktor.http.HttpMethod
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.copyAndClose
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
class FileDownloader {
suspend fun downloadFile(
serverUrl: String,
fileName: String,
destinationPath: String,
onProgress: ((Double, Double) -> Unit)?
) {
val outputFile = File(destinationPath)
outputFile.parentFile?.mkdirs()
val client = HttpClient(OkHttp)
client.use { it
it.prepareGet("$serverUrl/$fileName") {
method = HttpMethod.Get
onDownload { totalBytesSent, contentLength ->
if (totalBytesSent > 0 && contentLength != null){
onProgress?.let {
withContext(Dispatchers.Main) {
onProgress.invoke(totalBytesSent.toDouble(), contentLength.toDouble())
}
}
}
}
}.execute { response ->
val channel: ByteReadChannel = response.body()
channel.copyAndClose(outputFile.writeChannel())
}
}
}
}