Skip to main content

How to Upload and Download Large Files with Streaming

In this guide, we build a small file server with ZIO HTTP that accepts uploads of any size and sends files back as downloads, without ever holding a whole file in memory. By the end, you will have one server with two routes: POST /upload, which writes every file of a multipart upload to disk while its bytes are still arriving and rejects files above a size limit, and GET /files/{name}, which streams a stored file back to the client.

We start by turning on request streaming in the server configuration, then read the multipart body as a stream of parts and pipe each file part into a file. Next we cap the size of each file, and finally we serve the stored files as downloads.

The Problem​

A handler that reads an upload with Body#asMultipartForm gets the whole form at once, with each file as a Chunk[Byte] in memory. With the default server configuration it does not even get that far for a large file: the server collects every request body into memory before the handler runs, and it answers any body larger than 100 KiB with 413 Request Entity Too Large.

For example, a first upload handler often looks like this:

import java.nio.file.{Files, Paths}

import zio._

import zio.http._

val upload: Handler[Any, Response, Request, Response] =
handler { (req: Request) =>
for {
form <- req.body.asMultipartForm.orElseFail(Response.badRequest)
_ <- ZIO.foreachDiscard(form.formData) {
case file: FormField.Binary =>
ZIO.attemptBlocking {
Files.write(Paths.get("uploads", file.filename.getOrElse(file.name)), file.data.toArray)
}.orElseFail(Response.internalServerError)
case _ =>
ZIO.unit
}
} yield Response.ok
}

It works for small files in tests and fails in production. Raising the server's body limit makes larger files pass, but then every upload sits in memory in full before the first byte reaches the disk, so a few large uploads at the same time exhaust the heap. The handler also writes to a path built from the file name the client sent, so a name such as ../app.conf writes outside the upload directory.

ZIO HTTP can instead hand the request body to the handler as a stream, decode a multipart body part by part, and expose each file's bytes as a ZStream that goes straight into a file.

Prerequisites​

Everything in this guide comes with the zio-http dependency; it brings ZIO Streams along:

libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"

The code in this guide uses these imports:

import java.nio.file.{Files, Path, Paths}

import zio._

import zio.stream.ZSink

import zio.http._

This guide assumes you can define routes and handlers. The examples use curl to send requests.

Turn On Request Streaming​

By default, the server reads the whole request body into memory before it calls the handler and rejects bodies larger than 100 KiB. To pass the body to the handler as it arrives, we start the server with Server.Config#enableRequestStreaming:

val streamingServer: ZLayer[Any, Throwable, Server] =
Server.defaultWith(_.enableRequestStreaming)

Server.defaultWith takes the default configuration, port 8080 included, and applies the given change to it. With request streaming on, Body#asStream produces the bytes of the request as the client sends them, and the 100 KiB limit no longer applies. The server then applies no size limit to request bodies at all, so the handler has to set one; Limit the Upload Size shows how.

Stream Each File Part to Disk​

A browser form or curl -F sends files as a multipart/form-data body: a sequence of parts, each with its own headers and content. Body#asMultipartFormStream decodes such a body into a StreamingForm, and StreamingForm#fields returns its parts as a ZStream[Any, Throwable, FormField], in the order the client sent them. A part with a binary Content-Type, which is what browsers and curl send for a file, arrives as a FormField.StreamingBinary as soon as its headers are read; its data field is a ZStream[Any, Nothing, Byte] of the part's content that produces bytes as they reach the server.

Before we write a file, we need a name for it. The file name in a part comes straight from the client, so we accept only names made of letters, digits, dots, underscores and hyphens, and not starting with a dot. Such a name cannot contain a path separator or be .., so the file always stays inside the upload directory:

object Uploads {
val uploadDir: Path = Paths.get("uploads")

private val SafeName = "[A-Za-z0-9][A-Za-z0-9._-]*".r

def safeName(name: String): Option[String] =
name match {
case SafeName() => Some(name)
case _ => None
}
}

To save one file part, we run its data stream into ZSink.fromPath, which creates the file (or truncates an existing one), writes each chunk as it arrives, and returns the number of bytes written:

def saveFile(part: FormField.StreamingBinary): IO[Response, String] =
for {
name <- ZIO
.fromOption(part.filename.flatMap(Uploads.safeName))
.orElseFail(Response.badRequest("A file name may only contain letters, digits, dots, underscores and hyphens"))
written <- part.data
.run(ZSink.fromPath(Uploads.uploadDir.resolve(name)))
.orElseFail(Response.internalServerError(s"Could not write $name"))
} yield s"$name: $written bytes"

The upload handler decodes the body as a streaming form and saves its file parts one after another with ZStream#mapZIO. Other parts, such as ordinary text fields, are skipped. The handler answers with one line per saved file:

val upload: Handler[Any, Response, Request, Response] =
handler { (req: Request) =>
for {
form <- req.body.asMultipartFormStream
.orElseFail(Response.badRequest("Expected a multipart/form-data body"))
saved <- form.fields
.mapError(e => Response.badRequest(e.getMessage))
.mapZIO {
case part: FormField.StreamingBinary => saveFile(part).asSome
case _ => ZIO.none
}
.collectSome
.runCollect
} yield Response.text(saved.mkString("", "\n", "\n"))
}

Body#asMultipartFormStream fails when the request has no multipart Content-Type header with a boundary, which the handler turns into 400 Bad Request.

warning

The parts of a streaming form are decoded in order, from one connection, so the next part arrives only after the handler has read the data of the current one. Read each part's data inside the stream, as ZStream#mapZIO does above. A handler that first collects all the fields, for example with ZStream#runCollect, and reads their data afterwards never completes.

Parts that are not binary, such as ordinary text fields, are read into memory and arrive complete, as FormField.Text or FormField.Binary. This also applies to a file part sent without a Content-Type header, so a client that uploads large files must send one. curl and browsers always do.

To serve the upload route, we create the upload directory and start the server with the streaming layer:

val uploadRoutes: Routes[Any, Response] =
Routes(Method.POST / "upload" -> upload)

val runUploadServer: ZIO[Any, Throwable, Nothing] =
ZIO.attemptBlocking(Files.createDirectories(Uploads.uploadDir)) *>
Server.serve(uploadRoutes).provide(streamingServer)

With the server running, we upload a 1 GiB file, a 50 MiB file and a text field in one request:

curl -F "description=holiday" -F "file=@big.bin" -F "file=@video.mp4" http://localhost:8080/upload

The server writes both files to the uploads directory and lists them; the text field is skipped:

big.bin: 1073741824 bytes
video.mp4: 52428800 bytes

This upload completes with the server's heap limited to 128 MiB (-Xmx128m), because no part of the request is held in memory longer than it takes to write it to the file.

Runnable version, with the blocks of this section joined into one program and the shared Uploads.scala: Step4StreamToDiskExample.scala
zio-http-example/src/main/scala/example/largefiles/Uploads.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"

package example.largefiles

import java.nio.file.{Path, Paths}

/**
* Upload and Download Large Files with Streaming — Stream Each File Part to
* Disk
*
* The upload directory and the file name check shared by the examples of this
* guide. It has no `main`.
*/
object Uploads {
val uploadDir: Path = Paths.get("uploads")

private val SafeName = "[A-Za-z0-9][A-Za-z0-9._-]*".r

def safeName(name: String): Option[String] =
name match {
case SafeName() => Some(name)
case _ => None
}
}
zio-http-example/src/main/scala/example/largefiles/Step4StreamToDiskExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file Uploads.scala
// Run from this folder: scala-cli run Step4StreamToDiskExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.largefiles.Step4StreamToDiskExample"

package example.largefiles

import java.nio.file.Files

import zio._

import zio.stream.ZSink

import zio.http._

/**
* Upload and Download Large Files with Streaming — Stream Each File Part to
* Disk
*
* A server with request streaming turned on that writes every file part of a
* multipart upload to the `uploads` directory as its bytes arrive.
*/
object Step4StreamToDiskExample extends ZIOAppDefault {

def saveFile(part: FormField.StreamingBinary): IO[Response, String] =
for {
name <- ZIO
.fromOption(part.filename.flatMap(Uploads.safeName))
.orElseFail(Response.badRequest("A file name may only contain letters, digits, dots, underscores and hyphens"))
written <- part.data
.run(ZSink.fromPath(Uploads.uploadDir.resolve(name)))
.orElseFail(Response.internalServerError(s"Could not write $name"))
} yield s"$name: $written bytes"

val upload: Handler[Any, Response, Request, Response] =
handler { (req: Request) =>
for {
form <- req.body.asMultipartFormStream
.orElseFail(Response.badRequest("Expected a multipart/form-data body"))
saved <- form.fields
.mapError(e => Response.badRequest(e.getMessage))
.mapZIO {
case part: FormField.StreamingBinary => saveFile(part).asSome
case _ => ZIO.none
}
.collectSome
.runCollect
} yield Response.text(saved.mkString("", "\n", "\n"))
}

val routes: Routes[Any, Response] =
Routes(Method.POST / "upload" -> upload)

def run =
ZIO.attemptBlocking(Files.createDirectories(Uploads.uploadDir)) *>
Server.serve(routes).provide(Server.defaultWith(_.enableRequestStreaming))
}

Limit the Upload Size​

With request streaming on, the server accepts a request body of any size, so a client can fill the disk. We cap each file inside saveFile: ZStream#take passes at most maxFileSize + 1 bytes to the file, and when the file received more than maxFileSize bytes, we delete it and fail with 413 Request Entity Too Large:

val maxFileSize: Long = 100L * 1024 * 1024

def saveFile(part: FormField.StreamingBinary): IO[Response, String] =
for {
name <- ZIO
.fromOption(part.filename.flatMap(Uploads.safeName))
.orElseFail(Response.badRequest("A file name may only contain letters, digits, dots, underscores and hyphens"))
path = Uploads.uploadDir.resolve(name)
written <- part.data
.take(maxFileSize + 1)
.run(ZSink.fromPath(path))
.orElseFail(Response.internalServerError(s"Could not write $name"))
_ <- ZIO.when(written > maxFileSize) {
ZIO.attemptBlocking(Files.deleteIfExists(path)).ignore *>
ZIO.fail(Response.error(Status.RequestEntityTooLarge, s"$name is larger than $maxFileSize bytes"))
}
} yield s"$name: $written bytes"

Taking one byte more than the limit is what tells a file of exactly maxFileSize bytes apart from a larger one. The upload handler and the routes stay as they are; they call the new saveFile. When saveFile fails, the handler stops reading the request and the server answers with the error response:

curl -F "file=@huge.bin" http://localhost:8080/upload

For a 150 MiB file, the response has status 413 and this body, and no huge.bin is left in the upload directory:

huge.bin is larger than 104857600 bytes

Files already saved by the same request stay on disk. Delete them as well if a request must either store all of its files or none.

Runnable version, with the upload route of the previous section and the new saveFile: Step5LimitUploadSizeExample.scala
zio-http-example/src/main/scala/example/largefiles/Step5LimitUploadSizeExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file Uploads.scala
// Run from this folder: scala-cli run Step5LimitUploadSizeExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.largefiles.Step5LimitUploadSizeExample"

package example.largefiles

import java.nio.file.Files

import zio._

import zio.stream.ZSink

import zio.http._

/**
* Upload and Download Large Files with Streaming — Limit the Upload Size
*
* The streaming upload server from the previous section, with a 100 MiB limit
* per file: a larger file is deleted and the request fails with 413 Request
* Entity Too Large.
*/
object Step5LimitUploadSizeExample extends ZIOAppDefault {

val maxFileSize: Long = 100L * 1024 * 1024

def saveFile(part: FormField.StreamingBinary): IO[Response, String] =
for {
name <- ZIO
.fromOption(part.filename.flatMap(Uploads.safeName))
.orElseFail(Response.badRequest("A file name may only contain letters, digits, dots, underscores and hyphens"))
path = Uploads.uploadDir.resolve(name)
written <- part.data
.take(maxFileSize + 1)
.run(ZSink.fromPath(path))
.orElseFail(Response.internalServerError(s"Could not write $name"))
_ <- ZIO.when(written > maxFileSize) {
ZIO.attemptBlocking(Files.deleteIfExists(path)).ignore *>
ZIO.fail(Response.error(Status.RequestEntityTooLarge, s"$name is larger than $maxFileSize bytes"))
}
} yield s"$name: $written bytes"

val upload: Handler[Any, Response, Request, Response] =
handler { (req: Request) =>
for {
form <- req.body.asMultipartFormStream
.orElseFail(Response.badRequest("Expected a multipart/form-data body"))
saved <- form.fields
.mapError(e => Response.badRequest(e.getMessage))
.mapZIO {
case part: FormField.StreamingBinary => saveFile(part).asSome
case _ => ZIO.none
}
.collectSome
.runCollect
} yield Response.text(saved.mkString("", "\n", "\n"))
}

val routes: Routes[Any, Response] =
Routes(Method.POST / "upload" -> upload)

def run =
ZIO.attemptBlocking(Files.createDirectories(Uploads.uploadDir)) *>
Server.serve(routes).provide(Server.defaultWith(_.enableRequestStreaming))
}

Serve a File as a Download​

Body.fromFile creates a response body from a java.io.File without reading the file: when the server writes the response, it reads the file in chunks of 4 KiB and sends each chunk to the client, and it sets the Content-Length header from the file size. A Content-Disposition: attachment header, built with Header.ContentDisposition.attachment, tells the browser to save the response as a file with the given name instead of showing it.

The download handler checks the requested name with the same Uploads.safeName as the upload, so a request cannot reach a file outside the upload directory, and answers 404 Not Found for a name that is not a stored file:

val download: Handler[Any, Nothing, (String, Request), Response] =
handler { (name: String, _: Request) =>
Uploads.safeName(name).map(Uploads.uploadDir.resolve(_).toFile) match {
case Some(file) if file.isFile =>
Body.fromFile(file).map { body =>
Response(body = body)
.addHeader(Header.ContentType(MediaType.application.`octet-stream`))
.addHeader(Header.ContentDisposition.attachment(file.getName))
}
case _ =>
ZIO.succeed(Response.notFound(s"No file named $name"))
}
}

Downloads need no request streaming, so this route runs on the default server:

val downloadRoutes: Routes[Any, Response] =
Routes(Method.GET / "files" / string("name") -> download)

val runDownloadServer: ZIO[Any, Throwable, Nothing] =
Server.serve(downloadRoutes).provide(Server.default)

The -OJ options of curl save the response under the name from the Content-Disposition header, and -D - prints the response headers:

curl -D - -OJ http://localhost:8080/files/video.mp4

The headers carry the file size and the file name, and video.mp4 is saved in the current directory:

HTTP/1.1 200 OK
content-type: application/octet-stream
content-disposition: attachment; filename=video.mp4
date: Tue, 01 Dec 2026 18:06:51 GMT
content-length: 52428800

A 1 GiB download from this handler also completes with a 128 MiB heap.

tip

To serve files that the client may download in pieces, use Handler.fromFile instead of building the response yourself. It answers Range requests with 206 Partial Content, so an interrupted download can resume, and it sets the Content-Type from the file extension and the ETag and Last-Modified headers.

Putting It Together​

The complete example serves both routes from one server: the upload route with the size limit from Limit the Upload Size and the download route from Serve a File as a Download. It uses the streaming server layer for both, because the upload route needs it and the download route works on either:

zio-http-example/src/main/scala/example/largefiles/CompleteExample.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file Uploads.scala
// Run from this folder: scala-cli run CompleteExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.largefiles.CompleteExample"

package example.largefiles

import java.nio.file.Files

import zio._

import zio.stream.ZSink

import zio.http._

/**
* Upload and Download Large Files with Streaming — Putting It Together
*
* One server that streams uploaded files to disk with a size limit and sends
* them back as downloads.
*/
object CompleteExample extends ZIOAppDefault {

val maxFileSize: Long = 100L * 1024 * 1024

def saveFile(part: FormField.StreamingBinary): IO[Response, String] =
for {
name <- ZIO
.fromOption(part.filename.flatMap(Uploads.safeName))
.orElseFail(Response.badRequest("A file name may only contain letters, digits, dots, underscores and hyphens"))
path = Uploads.uploadDir.resolve(name)
written <- part.data
.take(maxFileSize + 1)
.run(ZSink.fromPath(path))
.orElseFail(Response.internalServerError(s"Could not write $name"))
_ <- ZIO.when(written > maxFileSize) {
ZIO.attemptBlocking(Files.deleteIfExists(path)).ignore *>
ZIO.fail(Response.error(Status.RequestEntityTooLarge, s"$name is larger than $maxFileSize bytes"))
}
} yield s"$name: $written bytes"

val upload: Handler[Any, Response, Request, Response] =
handler { (req: Request) =>
for {
form <- req.body.asMultipartFormStream
.orElseFail(Response.badRequest("Expected a multipart/form-data body"))
saved <- form.fields
.mapError(e => Response.badRequest(e.getMessage))
.mapZIO {
case part: FormField.StreamingBinary => saveFile(part).asSome
case _ => ZIO.none
}
.collectSome
.runCollect
} yield Response.text(saved.mkString("", "\n", "\n"))
}

val download: Handler[Any, Nothing, (String, Request), Response] =
handler { (name: String, _: Request) =>
Uploads.safeName(name).map(Uploads.uploadDir.resolve(_).toFile) match {
case Some(file) if file.isFile =>
Body.fromFile(file).map { body =>
Response(body = body)
.addHeader(Header.ContentType(MediaType.application.`octet-stream`))
.addHeader(Header.ContentDisposition.attachment(file.getName))
}
case _ =>
ZIO.succeed(Response.notFound(s"No file named $name"))
}
}

val routes: Routes[Any, Response] =
Routes(
Method.POST / "upload" -> upload,
Method.GET / "files" / string("name") -> download,
)

def run =
ZIO.attemptBlocking(Files.createDirectories(Uploads.uploadDir)) *>
Server.serve(routes).provide(Server.defaultWith(_.enableRequestStreaming))
}

Uploading a file and downloading it again returns the same bytes:

curl -F "file=@video.mp4" http://localhost:8080/upload
curl -OJ http://localhost:8080/files/video.mp4

The upload prints the saved file, and the download saves video.mp4 in the current directory:

video.mp4: 52428800 bytes

Running the Examples​

All runnable code from this guide is in zio-http-example/src/main/scala/example/largefiles/. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.largefiles.<ObjectName>". Each example starts a server on port 8080 and keeps uploaded files in an uploads directory under the working directory; send it the curl requests above.

Going Further​

  • Server covers the request streaming setting in more depth, with ZIO HTTP clients that upload a streamed body and a streamed multipart form.
  • Body lists the other ways to read a body, and From ZIO Streams shows Body.fromStream and Body.fromStreamChunked, which send a download that does not come from a file, such as a report that the server writes row by row.
  • Form describes every FormField case and how to build multipart forms.
  • The streaming examples and the multipart form data examples show more variations, such as echoing a streamed request body back to the client.