skip to content

In a Retrofit multipart method, how do @Part RequestBody, @Part MultipartBody.Part and @PartMap differ, and which one sends a filename?

level: middleimportance: should knowfreq 38%

answer

  1. who writes the part headers
  2. name only versus name and filename
  3. a map of dynamic fields
  4. other types meet a converter

basics

~20 s

A named @Part RequestBody gets a Content-Disposition with only a name; a MultipartBody.Part is sent exactly as built, so createFormData can add a filename; @PartMap adds one named part per map entry. Only MultipartBody.Part carries a filename.

solid answer

~40 s

For a named `@Part`, Retrofit writes the part headers itself: `Content-Disposition: form-data; name="caption"` plus `Content-Transfer-Encoding: binary` (the annotation's `encoding` default), and the body's own `Content-Type`. There is no `filename`, so a server that only treats a part as a file when it has one sees the photo as a plain field. A `MultipartBody.Part` is added untouched, which is why `createFormData(name, filename, body)` is the way to send a file. `@PartMap Map<String, RequestBody>` covers fields whose names are known only at run time; a null map, key or value fails the call, and its values cannot be `MultipartBody.Part`. Any value that is not a `RequestBody` goes through the first request-body converter that accepts it, so a `String` caption under a JSON converter arrives as `"Sunset"` in quotes.

go deeper

for a junior

Remember that only a MultipartBody.Part built with createFormData carries a filename; a named @Part RequestBody sends just a field name.

for a middle

Walk through the headers Retrofit writes for each form, how a non-RequestBody value reaches a converter, and the null rules for @Part versus @PartMap.

for a senior

Diagnose a server that receives a photo as a text field or a caption in quotes by reading the part headers, then fix the declaration rather than patching the server.

for a principal

Decide one convention for text parts across the codebase, explicit RequestBody or a scalars converter first, so the converter order never silently changes what an upload sends.

## Three ways to declare a part A Retrofit method marked `@Multipart` turns each annotated parameter into one part of a `multipart/form-data` body. A **part** is a header block followed by bytes; the header that matters is `Content-Disposition`, which carries the form field's `name` and, for files, a `filename`. Which parameter form you choose decides who writes that header. | declaration | headers Retrofit adds | filename | how the value becomes bytes | |---|---|---|---| | `@Part("caption") caption: RequestBody` | `Content-Disposition: form-data; name="caption"`, `Content-Transfer-Encoding: binary` | never | used as is, with its own `Content-Type` | | `@Part("meta") meta: Meta` (any other type) | the same two headers | never | the first request-body converter that accepts the type | | `@Part photo: MultipartBody.Part` | none | whatever the part was built with | the part's own body | | `@PartMap fields: Map<String, RequestBody>` | the same two headers, for each entry | never | per entry, as for a named `@Part` | ## Named parts and the missing filename For a named `@Part`, Retrofit builds the disposition string itself as `form-data; name="<value>"`. It has no way to add a filename: a `RequestBody` knows its bytes and media type but not where they came from. Many server-side multipart parsers decide "file or field" by whether `filename` is present, so a photo sent this way may be stored as a text field, or the endpoint answers that the file is missing. You will still see an old workaround in existing code: `@Part("photo\"; filename=\"photo.jpg")`. It works only because Retrofit pastes the name into the header without escaping it. It is unreadable and it breaks as soon as a filename contains a quote; `createFormData` quotes and escapes both values properly. ## MultipartBody.Part: the part you build yourself - `MultipartBody.Part.createFormData(name, filename, body)` writes `form-data; name="photo"; filename="IMG_0042.jpg"`; this is the normal way to send a file. - `MultipartBody.Part.createFormData(name, value)` builds a text field from a `String`, with no `Content-Type` line at all. - `MultipartBody.Part.create(headers, body)` takes custom headers but throws `IllegalArgumentException` if they contain `Content-Type` or `Content-Length`, which OkHttp derives from the body. - Retrofit adds **no** headers to these parts, so the `@Part` annotation's `encoding` has no effect on them, and the annotation must not carry a name. - `List<MultipartBody.Part>` and arrays are accepted, one part per element. ## @PartMap for fields known only at run time `@PartMap` takes a `Map<String, T>` and adds one named part per entry, which suits user-defined metadata or a form the server describes at run time. - Keys must be `String`; another key type fails the declaration. - Values are `RequestBody` or any type a converter can handle. `MultipartBody.Part` values are rejected with "@PartMap values cannot be MultipartBody.Part. Use @Part List<Part> or a different value type instead." - A null map, a null key or a null value fails the call with `IllegalArgumentException` when Retrofit builds the request. That differs from a null `@Part` argument, which is quietly skipped. - The annotation's `encoding` applies to every entry, and no entry gets a filename. ## Values that are not a RequestBody go through a converter A `@Part` or `@PartMap` value of any other type, a `String` included, is turned into a `RequestBody` by the first converter factory registered on the `Retrofit` instance that accepts the type. A JSON converter accepts nearly everything, so with only `GsonConverterFactory` registered, `@Part("caption") caption: String` set to `Sunset` is written as the JSON string `"Sunset"`, quotes included, with `Content-Type: application/json; charset=UTF-8`. The server stores the quotes. Two fixes are common: 1. Pass text parts as `RequestBody`, built with `toRequestBody("text/plain".toMediaType())`, so no converter is involved. 2. Register `ScalarsConverterFactory` ahead of the JSON factory; it turns a `String` into `text/plain; charset=UTF-8` bytes. Why the order matters belongs to the lesson on converters. Sending a model object as a JSON part on purpose is legitimate: a `metadata` part the server parses as JSON is exactly what the converter path is for. ## Nulls and transfer encoding - A null `@Part` argument is omitted from the body; if every part ends up omitted, OkHttp's `MultipartBody.Builder.build()` throws `IllegalStateException` ("Multipart body must have at least one part."). - `encoding` defaults to `"binary"`; `@Part(value = "image", encoding = "8-bit")` changes the `Content-Transfer-Encoding` header for that part. Modern server parsers rarely look at it.

  • Why does a caption declared as @Part("caption") String arrive at the server wrapped in quotes?
    A `String` is not a `RequestBody`, so Retrofit asks its converter factories for a request-body converter, and the first that accepts the type wins. A JSON converter such as Gson's accepts `String` and serialises it as a JSON string, quotes included, typed `application/json`. Send the caption as a `text/plain` `RequestBody`, or register the scalars converter before the JSON one.
  • When does a Retrofit @PartMap fail, and how does that differ from a null @Part?
    `@PartMap` fails at declaration time when the map's keys are not `String` or its values are `MultipartBody.Part`, and at call time with `IllegalArgumentException` when the map, a key or a value is null. A null `@Part` argument is not an error: Retrofit just leaves that part out of the body.

  • @Part("photo") RequestBody sends the file's name to the server automatically.
  • A String @Part is always sent as plain text.
  • @PartMap can hold MultipartBody.Part values to add files dynamically.
  • A null value inside a @PartMap is skipped like a null @Part.
  • Retrofit adds Content-Transfer-Encoding to MultipartBody.Part parameters too.
  • Embedding the filename inside the @Part name string is the intended API.