formFieldMultiMap

Signature

def formFieldMultiMap: Directive1[Map[String, List[String]]]

Description

Extracts all HTTP form fields at once as a multi-map of type Map[String, List[String]]Map<String, List<String>> mapping a form name to a list of all its values. Data posted from HTML Forms is either of type application/x-www-form-urlencoded or of type multipart/form-data.

This directive can be used if form fields can occur several times.

The order of values is not specified.

See formFields for an in-depth description.

Warning

Use of this directive can result in performance degradation or even in OutOfMemoryError s. See formFieldSeqformFieldList for details.

Example

Scala
sourceval route =
  formFieldMultiMap { fields =>
    complete("There are " +
      s"form fields ${fields.map(x => x._1 + " -> " + x._2.size).mkString(", ")}")
  }

// tests:
Post("/", FormData("color" -> "blue", "count" -> "42")) ~> route ~> check {
  responseAs[String] shouldEqual "There are form fields color -> 1, count -> 1"
}
Post("/", FormData("x" -> "23", "x" -> "4", "x" -> "89")) ~> route ~> check {
  responseAs[String] shouldEqual "There are form fields x -> 3"
}
Java
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.formFieldMultiMap;

final Function<Map<String, List<String>>, String> mapToString = map ->
  map.entrySet()
    .stream()
    .map(e -> e.getKey() + " -> " + e.getValue().size())
    .collect(Collectors.joining(", "));

final Route route = formFieldMultiMap(fields ->
  complete("There are form fields " + mapToString.apply(fields))
);

// test:
final FormData formDataDiffKey =
  FormData.create(
    Pair.create("color", "blue"),
    Pair.create("count", "42"));
testRoute(route).run(HttpRequest.POST("/").withEntity(formDataDiffKey.toEntity()))
  .assertEntity("There are form fields color -> 1, count -> 1");

final FormData formDataSameKey =
  FormData.create(
    Pair.create("x", "23"),
    Pair.create("x", "4"),
    Pair.create("x", "89"));
testRoute(route).run(HttpRequest.POST("/").withEntity(formDataSameKey.toEntity()))
  .assertEntity("There are form fields x -> 3");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.