
# Uploads

A `multipart/form-data` request carries files and form fields in one body. The starter reads it, keeps the files in temporary files, and binds each part to a controller parameter: a `MultipartFile`, a text field, raw bytes, or an object read from JSON.

## Why

A browser form with `enctype="multipart/form-data"`, `curl -F`, a Flutter app or a Feign client sends files this way. Reading that format by hand is long and easy to get wrong, and a careless reader holds whole uploads in memory or lets a client fill the disk. The starter:

- parses the body once per request, whoever asks first;
- streams each file to a private temporary file as it arrives, so no upload is held whole in memory;
- stops reading as soon as a limit is passed, and answers `413`;
- deletes the temporary files when the request ends, whatever the handler did.

## Example

```dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

class NewBook {
  const NewBook({required this.isbn, required this.title});

  @NotBlank()
  final String isbn;

  @NotBlank()
  final String title;
}

@RestController()
@RequestMapping('/api/books')
class BookUploadController {
  // A JSON part, a file, a text field, and optional extra files.
  @PostMapping.of(consumes: MediaType.multipartFormData)
  Future<String> create(
    @RequestPart('book') @Valid() NewBook book,
    @RequestPart('cover') MultipartFile cover,
    @RequestParam('note') String note, {
    @RequestPart('pages') List<MultipartFile>? pages,
  }) async {
    // Keep the cover: temporary files are deleted when the request ends.
    await cover.transferTo('/var/shop/covers/${book.isbn}.png');
    return '${book.title}: ${cover.size} bytes, ${pages?.length ?? 0} pages, $note';
  }

  // Several files under one name; an empty list when none was sent.
  @PostMapping('/attachments')
  List<String> attachments(@RequestPart('files') List<MultipartFile> files) => [
    for (final file in files) '${file.originalFilename}: ${file.size}',
  ];

  // The content in memory, for a small file.
  @PostMapping('/avatar')
  Future<int> avatar(@RequestPart() MultipartFile avatar) async {
    final bytes = await avatar.bytes;
    return bytes.length;
  }
}
```

```yaml
# lib/resources/application.yaml
spring:
  web:
    multipart:
      max-file-size: 5MB        # one file (or field); 1MB by default
      max-request-size: 20MB    # the whole request; 10MB by default
      max-part-count: 100       # files and fields together; 50 by default
      file-size-threshold: 64KB # smaller files stay in memory; 0B by default
      location: /var/tmp/shop   # where the private upload directory is made
```

The request a browser or `curl` sends:

```text
curl -F 'book={"isbn":"9780441013593","title":"Dune"};type=application/json' \
     -F cover=@dune.png -F note='first edition' \
     http://localhost:8080/api/books
```

## Binding parts to parameters

| Parameter | Value |
|---|---|
| `@RequestPart('cover') MultipartFile cover` | The file of that part. With several files under the name, the first. |
| `@RequestPart('files') List<MultipartFile> files` | Every file of that name, in the order they came. |
| `@RequestPart('note') String note` (or `int`, `bool`, an enum, ...) | A text field, converted like a request parameter. A file part of that name gives its content as text. |
| `@RequestPart('data') Uint8List data` (or `List<int>`) | The raw bytes of the part, a field or a file. |
| `@RequestPart('book') NewBook book` | The part's content read as JSON into the type through the `ObjectMapper`. With `@Valid()`, validated. |
| `@RequestPart() MultipartFile avatar` | Without a name, the part named like the parameter (`avatar`). |
| `@RequestParam('cover') MultipartFile cover` | The same as `@RequestPart` for files and lists of files. |
| `@RequestParam('note') String note` | A text field. The query string is looked at first, then the multipart fields. |
| `@RequestParam() Map<String, String> all` | The query parameters and the text fields together; the query wins on the same name. |
| `MultipartFile cover` without annotation | The file named like the parameter (`cover`). |

Rules:

- **Required or optional.** A part is required unless the parameter is nullable (`MultipartFile? cover`) or has a default value. A missing required part is a `400` with the detail `Required part 'cover' is not present.`.
- **Lists.** A missing `List<MultipartFile>` is a `400` when it is required, `null` when it is nullable, and an empty list when it is an optional named parameter that is not nullable.
- **Not multipart.** `@RequestPart` on a request that is not multipart is a `400` (`Failed to parse multipart request: the request is not a multipart request (Content-Type ...)`).
- **`consumes`** is not required. `consumes: MediaType.multipartFormData` makes a request with another `Content-Type` a `415` before the method is chosen, and documents the endpoint.
- **What is read.** Any `multipart/*` request that is not a `GET` is read. Only parts whose `Content-Disposition` has a `name` are kept; a part without one is skipped. A part with a `filename` (even an empty one) is a file; the others are fields.
- **Field text** is decoded as UTF-8, or Latin-1 when the part's `Content-Type` says `charset=iso-8859-1`.
- **A JSON part that does not parse** is a `400` (`JSON parse error in part "book": ...`). A `@Valid()` part that breaks a constraint is a `400` with the violations, as a `@RequestBody`.
- **When the body is read.** Only when a parameter or other code asks for the parts. A handler with no multipart parameter does not read the body at all.

## `MultipartFile`

`MultipartFile` comes from `spring_web_dart`.

| Member | Type | Meaning |
|---|---|---|
| `name` | `String` | The form field the file was sent in (`name=` of the part). Not the file name. |
| `originalFilename` | `String?` | The file name on the client's machine (`filename=`), or `null`. It comes from the client: never use it as a path as it is. |
| `contentType` | `String?` | The part's `Content-Type` (`image/png`), or `null`. The client's claim, not checked. |
| `size` | `int` | The size of the content, in bytes. |
| `isEmpty` | `bool` | Whether the content is empty. A browser sends an empty file part when no file was chosen. |
| `headers` | `HttpHeaders` | All the headers of the part. |
| `bytes` | `Future<Uint8List>` | The whole content, read into memory. For a large file use `openRead()` or `transferTo`. |
| `openRead()` | `Stream<List<int>>` | The content as a stream of chunks, read from the temporary file. Each call starts a new read. |
| `transferTo(String path)` | `Future<void>` | Saves the content as the file at `path`. The temporary file is moved there when possible (the same file system), else copied. |

Rules for `transferTo`:

- Call it once, after any other read. Once the temporary file has been moved, the file can no longer be read from its old place, and a second `transferTo` fails.
- A moved file is not deleted when the request ends: it is yours.
- Small files kept in memory (under `file-size-threshold`) are written to `path`.

Other implementations:

- `InMemoryMultipartFile(name, bytes, originalFilename:, contentType:, headers:)` and `InMemoryMultipartFile.fromString(name, text, ...)` hold the content in memory. Use them to call a controller or a Feign client from code. Their `transferTo` throws an `UnsupportedError`.
- `MockMultipartFile(name, originalFilename, contentType, bytes)` is the same with Spring's argument order, for tests.

## Limits and their errors

| Limit | Property | Default | Above it |
|---|---|---|---|
| One file, or one text field | `spring.web.multipart.max-file-size` | `1MB` | `413`: `Maximum upload size exceeded: the file "cover" is larger than 1048576 bytes.` (`part "note"` for a field) |
| The whole request | `spring.web.multipart.max-request-size` | `10MB` | `413`: `Maximum upload size exceeded: the request is larger than 10485760 bytes.` |
| The number of parts | `spring.web.multipart.max-part-count` | `50` | `413`: `Maximum upload size exceeded: the request has more than 50 parts.` |

- The answers are `ProblemDetail`s with status `413 Content Too Large`, from a `MaxUploadSizeExceededException`.
- **Reading stops at the limit.** The server does not read the rest of the body, and the temporary files written so far are deleted.
- **`server.max-http-request-body-size` does not apply** to a body the multipart resolver reads: `max-request-size` replaces it. Code that reads a multipart body in another way (a `@RequestBody() String`) keeps the server's limit.
- **A broken body** (no boundary, a part that never ends, part headers over 16 KB, a client that goes away in the middle) is a `400` from a `MultipartRequestException`: `Failed to parse multipart request: ...`. Nothing stays on disk.

Answer a limit in your own words with an `@ExceptionHandler`:

```dart
@ControllerAdvice()
class UploadErrors {
  @ExceptionHandler()
  ProblemDetail tooLarge(MaxUploadSizeExceededException e) =>
      ProblemDetail.forStatusAndDetail(
        HttpStatus.contentTooLarge,
        e.maxUploadSize < 0
            ? 'Too many files.'
            : 'Covers may have ${e.maxUploadSize ~/ 1024} KB at most.',
      );
}
```

`MaxUploadSizeExceededException.maxUploadSize` is the limit that was passed, in bytes, or `-1` for the number of parts. See [@ExceptionHandler](../errors/exception-handler.md).

## Temporary files

- Each file is streamed to a temporary file as it arrives, unless it fits under `file-size-threshold`.
- The files are in a directory of the process that only its user can open (`0700`), made once per process inside `location`, or inside the system's temporary directory. Each file has a random name (`upload_<32 hex digits>.tmp`) and is created exclusively, so another user of the machine can neither read an upload nor plant a file or a link under its name.
- When that directory disappears (the system cleans its temporary directory), a new one is made for the next upload.
- **They are deleted when the request ends**, after the controller method and its result, whatever the handler did. Keep a file with `transferTo`, or copy `openRead()` during the request.
- A filter that reads the parts itself (through the `multipartResolver` bean) of a request that reaches no controller should call `multipartResolver.cleanup(request)` when it is done.
- Without `dart:io` (on the web), files stay in memory.

## Properties

### `spring.web.multipart.enabled`

| Type | Default |
|---|---|
| `bool` | `true` |

Whether multipart requests are read. With `false`, they are not parsed at all: `@RequestPart` parameters answer `400`, and `MultipartFile` parameters too. Turn it off for a service that must never accept uploads, or when a filter or a library of your own reads the body.

```yaml
spring:
  web:
    multipart:
      enabled: false
```

### `spring.web.multipart.max-file-size`

| Type | Default |
|---|---|
| `DataSize` | `1MB` |

The largest single file, and also the largest text field. Above it the answer is `413`. `-1` means no limit. Sizes take a unit (`512KB`, `5MB`, `1GB`); a plain number is bytes. Raise it for photos, documents or videos. It should not be larger than `max-request-size`, which bounds the whole body anyway.

```yaml
spring:
  web:
    multipart:
      max-file-size: 25MB
```

### `spring.web.multipart.max-request-size`

| Type | Default |
|---|---|
| `DataSize` | `10MB` |

The largest multipart request as a whole: every part, with its headers and boundaries. Above it the answer is `413`. `-1` means no limit. This limit replaces `server.max-http-request-body-size` for uploads. Raise it together with `max-file-size` when a form sends several large files.

```yaml
spring:
  web:
    multipart:
      max-file-size: 25MB
      max-request-size: 100MB
```

### `spring.web.multipart.max-part-count`

| Type | Default |
|---|---|
| `int` | `50` |

The most parts a request may have, files and fields together. Above it the answer is `413`. `-1` means no limit. A request made of thousands of tiny parts costs the server work for each one; this limit stops it early. Raise it for forms with many fields or bulk uploads of many small files.

```yaml
spring:
  web:
    multipart:
      max-part-count: 500
```

This key is this starter's own. Spring Boot sets the same limit on Tomcat with `server.tomcat.max-part-count` (50).

### `spring.web.multipart.file-size-threshold`

| Type | Default |
|---|---|
| `DataSize` | `0B` |

Files up to this size stay in memory; larger ones go to a temporary file. With `0B` every file that has content goes to disk. Raise it (`64KB`) when most uploads are small and you want to skip the disk for them; keep it low when many uploads can arrive at once, since each one in memory costs memory. Ignored without `dart:io`, where files always stay in memory.

```yaml
spring:
  web:
    multipart:
      file-size-threshold: 64KB
```

### `spring.web.multipart.location`

| Type | Default |
|---|---|
| `String` | the system's temporary directory |

The directory in which the private upload directory is made. It is created when it is missing. A blank value is the default. Set it when the system's temporary directory is small (a `tmpfs` in memory), or to the same file system as the files' final place, so that `transferTo` moves the file instead of copying it.

```yaml
spring:
  web:
    multipart:
      location: /var/shop/uploads/tmp   # covers are kept in /var/shop/covers
```

## A resolver of your own

The starter declares a `multipartResolver` bean (`MultipartResolver`) built from these properties. Declare your own bean of that type to use other settings; the default then backs off.

```dart
@Configuration()
class UploadConfig {
  // The admin application takes uploads of any size.
  @Bean()
  MultipartResolver multipartResolver() => MultipartResolver(
    const MultipartProperties(maxFileSize: -1, maxRequestSize: -1),
  );
}
```

`MultipartProperties` has `enabled`, `maxFileSize`, `maxRequestSize`, `maxPartCount`, `fileSizeThreshold` (sizes in bytes) and `location`. `MultipartProperties.of(environment)` reads them from the properties.

A filter or an argument resolver that needs the parts asks the resolver. It reads the request once and hands the same result to every caller:

| Member of `MultipartResolver` | Meaning |
|---|---|
| `isMultipart(request)` | Whether it reads this request: enabled, not a `GET`, a `multipart/*` content type. |
| `resolve(request)` | The parts, as a `Future<MultipartRequest>`. Fails with the `413` and `400` exceptions above. |
| `cleanup(request)` | Deletes the temporary files of the request. |

| Member of `MultipartRequest` | Meaning |
|---|---|
| `files` | `Map<String, List<MultipartFile>>`: the file parts by field name. |
| `fields` | `Map<String, List<String>>`: the text of the other parts by field name. |
| `part(name)` | The headers and raw bytes of the first field part of that name, or `null`. |

## Testing

```dart
await app.mockMvc.multipart('/api/books', files: [
  MockMultipartFile('cover', 'dune.png', 'image/png', pngBytes),
  MockMultipartFile('book', null, 'application/json',
      utf8.encode('{"isbn": "9780441013593", "title": "Dune"}')),
], params: {'note': 'first edition'}).andExpect(status: 200);
```

A `MockMultipartFile` without a file name is a field part; with `application/json` it is a JSON part for `@RequestPart`. See [Testing](../testing.md).

## In Spring (Java)

```java
@PostMapping(path = "/api/books", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Book create(@RequestPart("book") @Valid NewBook book,
    @RequestPart("cover") MultipartFile cover,
    @RequestParam("note") String note) throws IOException {
  cover.transferTo(Path.of("/var/shop/covers", book.isbn() + ".png"));
  ...
}
```

```properties
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=20MB
```

Differences that matter:

- The keys are `spring.web.multipart.*`, Spring Boot's `spring.servlet.multipart.*` without the servlet. There is no servlet container: the starter parses the body itself.
- `max-part-count` is a key of this starter. Spring Boot has `server.tomcat.max-part-count`.
- Spring's `resolve-lazily` and `strict-servlet-compliance` do not exist. Parts are always read when first asked for.
- `required = false` is a nullable parameter in Dart.
- `getBytes()`, `getInputStream()` and `transferTo(File)` are `bytes`, `openRead()` and `transferTo(String path)`.

## See also

- [Downloads](downloads.md)
- [@RequestParam](../controllers/request-param.md)
- [@RequestBody](../controllers/request-body.md)
- [@ExceptionHandler](../errors/exception-handler.md)
- [DataSize](../../spring-core-dart/conversion/data-size.md)
- [All properties](../properties.md)
