In Retrofit, how do you declare a service method that uploads a profile photo file together with a text caption?
answer
- an encoding annotation on the method
- one annotation per parameter
- a verb that carries a body
- a ready-made part with a filename
- stream the file, never read it
basics
~10 sAnnotate the method with @Multipart and a body-carrying verb such as @POST, pass the photo as @Part MultipartBody.Part built by createFormData with a filename, and pass the caption as @Part("caption") RequestBody.
solid answer
~40 sI put `@Multipart` and `@POST` (or `@PUT`/`@PATCH`) on the method and declare each part as a parameter annotated `@Part`. The photo is a `MultipartBody.Part` from `MultipartBody.Part.createFormData("photo", file.name, file.asRequestBody("image/jpeg".toMediaType()))`; its `@Part` carries no name, because the part already has its own `Content-Disposition`. The caption is `@Part("caption") caption: RequestBody`, made with `toRequestBody("text/plain".toMediaType())`. `asRequestBody` copies the file only when OkHttp writes the request, so the photo never sits in memory. Retrofit 3 depends on OkHttp 4.12, so these Kotlin extensions replace OkHttp 3's static `RequestBody.create`. Retrofit checks the declaration the first time the method is called, or in `create()` with `validateEagerly(true)`, and throws `IllegalArgumentException` for `@Multipart` on a `@GET`, a method with no `@Part`, or a `@Body` beside the parts.
code
kotlin · 30 linesimport java.io.File
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
data class ProfileResponse(val photoUrl: String)
interface ProfileApi {
@Multipart
@POST("me/photo")
suspend fun uploadPhoto(
@Part photo: MultipartBody.Part,
@Part("caption") caption: RequestBody?,
): ProfileResponse
}
suspend fun uploadProfilePhoto(api: ProfileApi, file: File, captionText: String?): ProfileResponse {
val photo = MultipartBody.Part.createFormData(
"photo",
file.name,
file.asRequestBody("image/jpeg".toMediaType()),
)
val caption = captionText?.toRequestBody("text/plain".toMediaType())
return api.uploadPhoto(photo, caption)
}go deeper
Recall the three pieces: @Multipart with a body-carrying verb, @Part per parameter, and createFormData with a filename for the file. Name the caption part, never the file part.
Explain what Retrofit builds from the declaration: a multipart/form-data body with one part per argument, a filename only from createFormData, and a file body that streams when OkHttp writes it.
Show you prevent production surprises: validateEagerly in tests catches a broken declaration before the first real call, and file bodies stay streamed so a large upload never inflates the heap.
Treat upload endpoints as a shared client convention: one helper that builds file parts with names, filenames and media types, so each feature team does not reinvent part headers differently.
## What a multipart request is A **multipart/form-data** body is a sequence of **parts** separated by a boundary string. Each part has a small header block of its own, at least a `Content-Disposition` naming the form field, followed by its bytes. It is how a browser's file-upload form sends a file and some text fields in one request, and it is what most upload endpoints expect from a mobile client too. In Retrofit you never write the boundary yourself. When a service method carries `@Multipart`, Retrofit creates an OkHttp `MultipartBody.Builder`, sets its type to `MultipartBody.FORM` (`multipart/form-data`) and adds one part for every `@Part` argument when the call is made. ## Declaring the method ```kotlin @Multipart @POST("me/photo") suspend fun uploadPhoto( @Part photo: MultipartBody.Part, @Part("caption") caption: RequestBody, ): ProfileResponse ``` The rules Retrofit enforces on a declaration like this: - `@Multipart` goes on the **method**, beside an HTTP method that carries a body: `@POST`, `@PUT`, `@PATCH`, or `@HTTP` with `hasBody = true`. - Every part is a parameter annotated `@Part` (or `@PartMap`), and there must be at least one. - A `MultipartBody.Part` parameter takes `@Part` **with no name**; any other type needs one, as in `@Part("caption")`. - `@Body`, `@Field` and `@FormUrlEncoded` cannot appear in the same method: a method has exactly one body encoding. - The return type is independent of the parts: a `suspend` function, a `Call<T>` or an RxJava type all send the same body. - A list or array of parts is allowed: `@Part photos: List<MultipartBody.Part>` adds each element as its own part. ## Building the photo part `MultipartBody.Part.createFormData("photo", file.name, body)` produces a part whose header reads `Content-Disposition: form-data; name="photo"; filename="IMG_0042.jpg"`. The **filename** matters: many server-side multipart parsers only treat a part as an uploaded file when it has one. The body is `file.asRequestBody("image/jpeg".toMediaType())`. This OkHttp extension reports the file's length as `contentLength()` and copies the file into the network sink inside `writeTo()`, which runs when the call executes. Nothing is read when you create it, so a 12 MB photo never sits in the app's heap. **Version note.** Retrofit 3.0.0 moved its OkHttp dependency from 3.14 to 4.12, the Kotlin rewrite of OkHttp. The extension functions `asRequestBody`, `toRequestBody` and `toMediaType` are therefore always on the classpath, and OkHttp 3's static `RequestBody.create(MediaType, File)` is deprecated in their favour. ## Building the caption part The caption is a short text part: `captionText.toRequestBody("text/plain".toMediaType())`, passed as `@Part("caption") caption: RequestBody`. Retrofit writes `Content-Disposition: form-data; name="caption"` plus the body's `Content-Type`. A `RequestBody` is used exactly as given; a `String` parameter would instead go through a request-body converter, and a JSON converter turns it into a quoted JSON string, which the lesson on Retrofit's converters explains. Passing `null` for a `@Part` argument simply leaves that part out, so an optional caption can be a nullable parameter. ## When Retrofit checks the declaration Retrofit parses a method's annotations the first time the method is invoked and caches the result. `Retrofit.Builder().validateEagerly(true)` moves the check into `create()`, which is useful in a debug build or a unit test. A broken declaration throws `IllegalArgumentException` whose message names the method: | mistake | Retrofit's message (abridged) | |---|---| | `@Multipart` with `@GET` | Multipart can only be specified on HTTP methods with request body | | no `@Part` parameter | Multipart method must contain at least one @Part | | a `RequestBody` part with no name | @Part annotation must supply a name or use MultipartBody.Part parameter type | | a name on a `MultipartBody.Part` | @Part parameters using the MultipartBody.Part must not include a part name | | `@Body` beside the parts | @Body parameters cannot be used with form or multi-part encoding | ## Mistakes worth recognising 1. Reading the file with `readBytes()` and sending the array: the whole image is held in memory for the length of the upload. 2. Building the photo with `@Part("photo") RequestBody`: valid, but the part has no filename, so a server expecting a file may store it as a text field or reject it. 3. Reaching for `@Field` for the caption: form fields belong to `@FormUrlEncoded` methods and are rejected here. 4. Assuming a misdeclared method fails at startup: without `validateEagerly`, the error appears on the first call, often in production code paths nobody tested.
- Why must a MultipartBody.Part parameter have no name in its @Part annotation?Retrofit adds a `MultipartBody.Part` exactly as built, and `createFormData` has already written the field name and filename into its `Content-Disposition`. A name on the annotation would describe a second header, so Retrofit rejects the method with "@Part parameters using the MultipartBody.Part must not include a part name in the annotation." The reverse rule holds too: a `RequestBody` part with no name fails because Retrofit would have nothing to put in `name=`.
- What happens if every @Part argument passed to a Retrofit multipart method is null?Retrofit skips each null part, so the builder ends up empty. Its own declaration check passed, because the method does declare a `@Part`, but OkHttp's `MultipartBody.Builder.build()` then throws `IllegalStateException` with "Multipart body must have at least one part." Keep at least one part non-null, typically the file.
- How do you send several photos in one Retrofit multipart request?Declare `@Part photos: List<MultipartBody.Part>` (an array works too) and build one part per file with `createFormData`, usually repeating the same field name the server reads as a list. Retrofit adds every element as a separate part; a null element is skipped.
- Read the photo with readBytes() and send the byte array as the part.
- Give a MultipartBody.Part parameter a name in @Part as well.
- Put @Body and @Multipart on the same method to send a prebuilt body.
- @Multipart works with @GET as long as the method declares parts.
- Send the caption with @Field inside the multipart method.
- A misdeclared multipart method always fails when create() is called.
Assumes Retrofit 3.0.0, which depends on OkHttp 4.12, so the Kotlin extensions asRequestBody and toRequestBody replace OkHttp 3's static RequestBody.create.