fileUpload

fileUpload

Signature

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

// adding integers as a service ;)
val route =
  extractRequestContext { ctx =>
    implicit val materializer = ctx.materializer
    implicit val ec = ctx.executionContext

    fileUpload("csv") {
      case (metadata, byteSource) =>

        val sumF: Future[Int] =
          // sum the numbers as they arrive so that we can
          // accept any size of file
          byteSource.via(Framing.delimiter(ByteString("\n"), 1024))
            .mapConcat(_.utf8String.split(",").toVector)
            .map(_.toInt)
            .runFold(0) { (acc, n) => acc + n }

        onSuccess(sumF) { sum => complete(s"Sum: $sum") }
    }
  }

// tests:
val multipartForm =
  Multipart.FormData(Multipart.FormData.BodyPart.Strict(
    "csv",
    HttpEntity(ContentTypes.`text/plain(UTF-8)`, "2,3,5\n7,11,13,17,23\n29,31,37\n"),
    Map("filename" -> "primes.csv")))

Post("/", multipartForm) ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "Sum: 178"
}
curl --form "csv=@uploadFile.txt" http://<host>:<port>

Contents