Skip to content

Instantly share code, notes, and snippets.

@stepango
Last active March 30, 2021 13:30
Show Gist options
  • Save stepango/d93da8351be3f2248a800bd0877b1252 to your computer and use it in GitHub Desktop.
Save stepango/d93da8351be3f2248a800bd0877b1252 to your computer and use it in GitHub Desktop.
Kotlin Retrofit2 RequestBody from FileDescriptor
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)
}
}
}
@jemshit
Copy link

jemshit commented Mar 30, 2021

Should not pass FileDescriptor around, because its owner ParcelFileDescriptor/AssetFileDescriptor must be closed when FileDescriptor InputStream is closed.
Better way is passing Uri and create ParcelFileDescriptor/AssetFileDescriptor when you need InputStream then close ParcelFileDescriptor/AssetFileDescriptor. (AutoCloseInputStream (ParcelFileDescriptor/AssetFileDescriptor) class can be used for closing)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment