Created
November 6, 2017 09:02
-
-
Save gedorinku/043b89c47de00a49471e99800cfb7b0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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