Skip to content

Instantly share code, notes, and snippets.

@ywett02
Last active February 2, 2019 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ywett02/993eed968126f58637a5ad1a7965701d to your computer and use it in GitHub Desktop.
Save ywett02/993eed968126f58637a5ad1a7965701d to your computer and use it in GitHub Desktop.
File upload with progress
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.Okio
import java.io.File
import kotlin.math.roundToInt
class ProgressByteArrayRequestBody(
private val contentType: MediaType,
private val array: ByteArray,
private var readCount: Int = 0,
private val progressCallback: (progress: Int) -> Unit
) : RequestBody() {
private val segmentSize = 2048
override fun contentType(): MediaType? = contentType
override fun contentLength(): Long = array.size.toLong()
override fun writeTo(sink: BufferedSink) {
readCount++
var uploaded = 0
var read: Int
var buffer: ByteArray
while (uploaded < contentLength()) {
read = if (contentLength().toInt() - uploaded > segmentSize) segmentSize else contentLength().toInt() - uploaded
buffer = array.copyOfRange(uploaded, (uploaded + read))
if (readCount > 1) progressCallback.invoke((100 * uploaded / contentLength()).toInt())
uploaded += read
sink.write(buffer, 0, read)
}
}
}
class ProgressFileRequestBody(
private val file: File,
private val contentType: MediaType,
private var readCount: Int = 0,
private val progressCallback: (progress: Int) -> Unit
) : RequestBody() {
private val segmentSize = 2048L
override fun contentType(): MediaType? = contentType
override fun contentLength(): Long = file.length()
override fun writeTo(sink: BufferedSink) {
readCount++
Okio.source(file).use {
var total: Long = 0
var read: Long = 0
while ({ read = it.read(sink.buffer(), segmentSize); read }() != -1L) {
total += read
sink.flush()
if (readCount > 1) progressCallback.invoke((100 * total / contentLength().toFloat()).roundToInt())
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment