Last active
March 30, 2021 13:30
-
-
Save stepango/d93da8351be3f2248a800bd0877b1252 to your computer and use it in GitHub Desktop.
Kotlin Retrofit2 RequestBody from FileDescriptor
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
fun requestBody(fd: FileDescriptor) = object : RequestBody() { | |
override fun contentType(): MediaType = MediaType.parse("multipart/form-data") | |
override fun writeTo(sink: BufferedSink) { | |
Okio.source(FileInputStream(fd)).use { source -> | |
sink.writeAll(source) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should not pass
FileDescriptor
around, because its ownerParcelFileDescriptor
/AssetFileDescriptor
must be closed whenFileDescriptor
InputStream
is closed.Better way is passing
Uri
and createParcelFileDescriptor
/AssetFileDescriptor
when you needInputStream
then closeParcelFileDescriptor
/AssetFileDescriptor
. (AutoCloseInputStream (ParcelFileDescriptor/AssetFileDescriptor)
class can be used for closing)