Skip to content

Instantly share code, notes, and snippets.

@gedorinku
Created November 6, 2017 09:02
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 gedorinku/043b89c47de00a49471e99800cfb7b0c to your computer and use it in GitHub Desktop.
Save gedorinku/043b89c47de00a49471e99800cfb7b0c to your computer and use it in GitHub Desktop.
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.Okio
fun createRequestBody(uri: Uri, context: Context): RequestBody {
val contentResolver = context.contentResolver
val contentType = MediaType.parse(contentResolver.getType(uri))
val projection = arrayOf(MediaStore.MediaColumns.SIZE)
val length = contentResolver
.query(uri, projection, null, null, null)
?.use {
if (it.moveToFirst()) {
it.getLong(0)
} else {
null
}
} ?: throw IllegalArgumentException("uriからファイルサイズを取得できません")
return object : RequestBody() {
override fun contentLength(): Long = length
override fun contentType(): MediaType? = contentType
override fun writeTo(sink: BufferedSink) {
Okio
.source(context.contentResolver.openInputStream(uri))
.use {
sink.writeAll(it)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment