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:

Example

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;
  }
}
# 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:

curl -F 'book={"isbn":"9780441013593","title":"Dune"};type=application/json' \
     -F [email protected] -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:

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:

Other implementations:

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.

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

@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.

Temporary files

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.

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.

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.

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.

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.

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.

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.

@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

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.

In Spring (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"));
  ...
}
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=20MB

Differences that matter:

See also