1+ package com.troplo.privateuploader.api
2+
3+ import android.content.ContentResolver
4+ import android.content.Context
5+ import android.net.Uri
6+ import android.os.Handler
7+ import android.os.Looper
8+ import android.util.Log
9+ import okhttp3.MediaType
10+ import okhttp3.MediaType.Companion.toMediaTypeOrNull
11+ import okhttp3.RequestBody
12+ import okio.BufferedSink
13+ import java.io.File
14+ import java.io.FileInputStream
15+ import java.io.IOException
16+ import java.io.InputStream
17+ import java.lang.ref.WeakReference
18+
19+
20+ class RequestBodyWithProgress (
21+ private val file : File ,
22+ private val contentType : ContentType ,
23+ private val progressCallback : ((progress: Float )-> Unit )?
24+ ) : RequestBody() {
25+
26+ override fun contentType (): MediaType ? = contentType.description.toMediaTypeOrNull()
27+
28+ override fun contentLength (): Long = file.length()
29+
30+ override fun writeTo (sink : BufferedSink ) {
31+ val fileLength = contentLength()
32+ val buffer = ByteArray (DEFAULT_BUFFER_SIZE )
33+ val inSt = FileInputStream (file)
34+ var uploaded = 0L
35+ inSt.use {
36+ var read: Int = inSt.read(buffer)
37+ val handler = Handler (Looper .getMainLooper())
38+ while (read != - 1 ) {
39+ progressCallback?.let {
40+ uploaded + = read
41+ val progress = (uploaded.toDouble() / fileLength.toDouble()).toFloat()
42+ handler.post { it(progress) }
43+
44+ sink.write(buffer, 0 , read)
45+ }
46+ read = inSt.read(buffer)
47+ }
48+ }
49+ }
50+
51+ enum class ContentType (val description : String ) {
52+ PNG_IMAGE (" image/png" ),
53+ JPG_IMAGE (" image/jpg" ),
54+ IMAGE (" image/*" )
55+ }
56+ }
0 commit comments