fileUpload

Description

Simple access to the stream of bytes for a file uploaded as a multipart form together with metadata about the upload as extracted value.

If there is no field with the given name the request will be rejected, if there are multiple file parts with the same name, the first one will be used and the subsequent ones ignored.

Example

final Route route = extractRequestContext(ctx -> {
  // function (FileInfo, Source<ByteString,Object>) => Route to process the file contents
  BiFunction<FileInfo, Source<ByteString, Object>, Route> processUploadedFile =
    (metadata, byteSource) -> {
      CompletionStage<Integer> sumF = byteSource.via(Framing.delimiter(
        ByteString.fromString("\n"), 1024))
        .mapConcat(bs -> Arrays.asList(bs.utf8String().split(",")))
        .map(s -> Integer.parseInt(s))
        .runFold(0, (acc, n) -> acc + n, ctx.getMaterializer());
      return onSuccess(() -> sumF, sum -> complete("Sum: " + sum));
    };
  return fileUpload("csv", processUploadedFile);
});

Map<String, String> filenameMapping = new HashMap<>();
filenameMapping.put("filename", "primes.csv");

akka.http.javadsl.model.Multipart.FormData multipartForm =
  Multiparts.createStrictFormDataFromParts(
    Multiparts.createFormDataBodyPartStrict("csv",
      HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8,
        "2,3,5\n7,11,13,17,23\n29,31,37\n"), filenameMapping));

// test:
testRoute(route).run(HttpRequest.POST("/").withEntity(
  multipartForm.toEntity(BodyPartRenderer.randomBoundaryWithDefaults())))
  .assertStatusCode(StatusCodes.OK).assertEntityAs(Unmarshaller.entityToString(), "Sum: 178");
curl --form "[email protected]" http://<host>:<port>
The source code for this page can be found here.