With Retrofit, how do you upload a profile photo the user picked as a content:// Uri without reading the whole file into memory?
answer
- a Uri is not a File
- the tempting byte array
- a body that copies a stream
- open it where it is written
- a size you may not know
basics
~20 sWrite a RequestBody whose writeTo() opens contentResolver.openInputStream(uri) and copies its source into the sink, report the size from OpenableColumns.SIZE or -1, and wrap it with createFormData. Reading the Uri into a byte array is the classic mistake.
solid answer
~40 sA photo-picker result is a `content://` Uri, not a file path, so `File.asRequestBody` does not apply, and `openInputStream(uri)!!.readBytes().toRequestBody(type)` holds the whole photo in the heap for the length of the upload. I write a small `RequestBody`: `contentType()` from `contentResolver.getType(uri)`, `contentLength()` from the `OpenableColumns.SIZE` column or `-1`, and a `writeTo()` that opens a **fresh** stream and copies it with `sink.writeAll(input.source())`. Opening inside `writeTo()` matters because OkHttp can write a body twice, for body logging or a retransmission, and a stream opened once would be drained. An unknown length makes the whole multipart length unknown, so over HTTP/1.1 OkHttp sends it chunked; a wrong length fails the call with a `ProtocolException`. With OkHttp 5 on the classpath (Retrofit 3 itself depends on 4.12), `FileDescriptor.toRequestBody()` is a ready-made, one-shot alternative.
code
kotlin · 34 linesimport android.content.ContentResolver
import android.net.Uri
import android.provider.OpenableColumns
import java.io.IOException
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okio.BufferedSink
import okio.source
class ContentUriRequestBody(
private val resolver: ContentResolver,
private val uri: Uri,
) : RequestBody() {
private val size: Long by lazy {
resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { c ->
if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else -1L
} ?: -1L
}
override fun contentType(): MediaType? = resolver.getType(uri)?.toMediaTypeOrNull()
override fun contentLength(): Long = size
override fun writeTo(sink: BufferedSink) {
// A fresh stream on every pass: OkHttp may call writeTo() more than once.
val input = resolver.openInputStream(uri) ?: throw IOException("Cannot open $uri")
input.source().use { source -> sink.writeAll(source) }
}
}
fun photoPart(resolver: ContentResolver, uri: Uri, displayName: String): MultipartBody.Part =
MultipartBody.Part.createFormData("photo", displayName, ContentUriRequestBody(resolver, uri))go deeper
Recall that a picked photo arrives as a content Uri, not a File, and that reading it into a byte array before uploading is the mistake to avoid.
Explain the custom RequestBody: type from the resolver, size from OpenableColumns or -1, and writeTo() copying the stream's source into the sink.
Show the production edge cases: a fresh stream per writeTo() pass, chunked uploads when the size is unknown, ProtocolException on a wrong size, and OkHttp 5 for FileDescriptor bodies.
Choose a single upload input path for the app, streamed Uri or cache copy, weighing chunked-upload support on the server against disk use and cleanup.
## Why a content Uri needs its own RequestBody The system photo picker and the Storage Access Framework hand an app a **content Uri** (`content://...`), not a path on disk. The bytes belong to another app's content provider and are read through `ContentResolver`. That rules out the usual file helper: OkHttp's `File.asRequestBody()` needs a `java.io.File`, and `File(uri.path)` does not point at the photo, because a content Uri's path is not a file-system path. The tempting shortcut is `contentResolver.openInputStream(uri)!!.readBytes().toRequestBody(type)`. It works in a demo and fails in production: the whole photo, often tens of megabytes from a modern camera, sits in a byte array for as long as the upload takes, and a video picked the same way ends in an `OutOfMemoryError`. Decoding the image into a `Bitmap` first is worse still, because the decoded pixels are far larger than the file. ## A streaming RequestBody for a Uri ```kotlin class ContentUriRequestBody( private val resolver: ContentResolver, private val uri: Uri, ) : RequestBody() { private val size: Long by lazy { resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else -1L } ?: -1L } override fun contentType(): MediaType? = resolver.getType(uri)?.toMediaTypeOrNull() override fun contentLength(): Long = size override fun writeTo(sink: BufferedSink) { val input = resolver.openInputStream(uri) ?: throw IOException("Cannot open $uri") input.source().use { source -> sink.writeAll(source) } } } ``` - `contentType()` asks the provider for the MIME type; `toMediaTypeOrNull()` tolerates a value OkHttp cannot parse. - `contentLength()` reads the provider's `OpenableColumns.SIZE` once and caches it; a provider may not know the size, and then the body says `-1`. - `writeTo()` copies the stream segment by segment, so memory stays flat whatever the photo's size, and `use` closes the stream even when the write fails. The part is then built the usual way: `MultipartBody.Part.createFormData("photo", displayName, ContentUriRequestBody(resolver, uri))`, passed to a `@Multipart` method as `@Part photo: MultipartBody.Part`. ## Open the stream inside writeTo() OkHttp does not promise to call `writeTo()` only once. An `HttpLoggingInterceptor` at `Level.BODY` writes the body into a buffer before the network write, and OkHttp retransmits a body after a failure on a stale pooled connection or a follow-up such as a 401 answered by its `Authenticator`. A stream opened in the constructor is drained by the first pass, so the second pass writes nothing. Opening a new stream on every call to `writeTo()` makes each pass complete. ## When the length is wrong or unknown | `contentLength()` returns | what OkHttp does | |---|---| | the exact size | sends `Content-Length` for the whole multipart body | | `-1` | the multipart body's length is unknown too, so OkHttp sets `Transfer-Encoding: chunked` (HTTP/2 frames the body without either) | | a size that is too small | the write fails with `ProtocolException` "expected N bytes but received M" | | a size that is too large | closing the body fails with `ProtocolException` "unexpected end of stream" | Some upload endpoints and proxies refuse chunked request bodies, so when `SIZE` is missing it can be worth copying the photo to the app's cache directory first and sending that file with `File.asRequestBody()`, which always knows its length. That costs disk space and a copy, not heap. ## Ready-made alternatives and their versions - **Copy to a cache file**, then `file.asRequestBody(type)`: simplest, known length, safe to write twice; the copy must be deleted afterwards. - **`FileDescriptor.toRequestBody()`** from OkHttp 5: open `resolver.openFileDescriptor(uri, "r")` and pass its `fileDescriptor`. It became stable in OkHttp 5's alpha line and is not part of OkHttp 4.12, the version Retrofit 3.0.0 depends on, so the app must declare OkHttp 5 itself. The body is **one-shot** (no logging of its bytes, no retransmission) and reports no length, so it is sent chunked; keep the `ParcelFileDescriptor` open until the call finishes, then close it. - **`Path.asRequestBody(fileSystem)`**, also stable only in OkHttp 5, suits files the app can reach through an Okio file system, not provider-owned Uris. ## Checklist 1. Never call `readBytes()` or decode a `Bitmap` just to upload. 2. Open the input stream inside `writeTo()`, every time. 3. Report the real size, or `-1`, never a guess. 4. Send a filename with `createFormData`, from the provider's display name rather than the Uri. 5. Keeping the upload alive when the screen or process goes away belongs to background work scheduling, and resuming a half-sent photo to a resumable-upload design; neither is solved inside the request body.
- What goes wrong if the InputStream is opened once in the RequestBody's constructor?The first call to `writeTo()` drains it. If OkHttp writes the body again, for a body-level logging interceptor or a retransmission after a stale connection, the second pass sends nothing, and with a declared length OkHttp fails with `ProtocolException` "unexpected end of stream". It also leaves a stream open between building the request and sending it.
- When would you copy the picked photo to a cache file instead of streaming the Uri?When the provider cannot report a size and the endpoint rejects chunked uploads, or when the same bytes must be sent several times. A cache file gives `File.asRequestBody()` an exact length and can be rewritten safely; the cost is disk space and a copy, and the file must be deleted when the upload ends.
- Read the Uri into a byte array; photos are small enough.
- Use File(uri.path) with asRequestBody for a content Uri.
- Decode the picked image into a Bitmap and compress it just to upload it.
- Open the input stream once in the constructor and reuse it.
- Return an estimated contentLength() when the provider reports no size.
- FileDescriptor.toRequestBody() is available with Retrofit 3's own OkHttp 4.12.
Assumes Retrofit 3.0.0, which depends on OkHttp 4.12; FileDescriptor.toRequestBody() and Path.asRequestBody() are stable only in OkHttp 5, which the app must declare itself.