File uploads

suggest change

Files reach a server in one of two ways:

This article shows both directions with Ktor:

All examples were compiled with Kotlin 2.4.21 and Ktor 3.6.0, and run on JDK 25. Each program starts a server on a free port (port = 0) and calls it from the same process, so you can run it as-is.

Dependencies

val ktorVersion = "3.6.0"

dependencies {
    implementation("io.ktor:ktor-server-netty:$ktorVersion")
    implementation("io.ktor:ktor-server-status-pages:$ktorVersion")
    implementation("io.ktor:ktor-server-body-limit:$ktorVersion") // RequestBodyLimit
    implementation("io.ktor:ktor-client-cio:$ktorVersion")
    implementation("org.slf4j:slf4j-simple:2.0.17")
}

What a multipart request looks like

On the wire a multipart body is a list of parts separated by a boundary string. The client picks the boundary and announces it in the Content-Type header:

POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----XyZ

------XyZ
Content-Disposition: form-data; name="title"

Holiday photos
------XyZ
Content-Disposition: form-data; name="photo"; filename="beach.jpg"
Content-Type: image/jpeg

<raw JPEG bytes>
------XyZ--

Each part has a Content-Disposition header with the form field name. File parts also have a filename and usually a Content-Type. Lines end with CRLF, and the last boundary has a trailing --.

In a browser, you get this format from a form with enctype="multipart/form-data". Without it the browser sends only the file name:

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="text" name="title">
  <input type="file" name="photo" accept="image/*" multiple>
  <button>Upload</button>
</form>

Receiving uploads with Ktor

call.receiveMultipart() returns a MultiPartData, a stream of parts. forEachPart goes through them in the order the client sent them:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.forms.formData
import io.ktor.client.request.forms.submitFormWithBinaryData
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.content.PartData
import io.ktor.http.content.forEachPart
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.receiveMultipart
import io.ktor.server.response.respondText
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.copyAndClose
import kotlinx.coroutines.runBlocking
import java.io.File
import kotlin.io.path.createTempDirectory

fun main() {
    val uploadDir = createTempDirectory("uploads").toFile()

    val server = embeddedServer(Netty, port = 0) {
        routing {
            post("/upload") {
                val report = StringBuilder()
                val multipart = call.receiveMultipart()
                multipart.forEachPart { part ->
                    when (part) {
                        is PartData.FormItem ->
                            report.appendLine("field ${part.name} = ${part.value}")
                        is PartData.FileItem -> {
                            val file = File(uploadDir, "upload-${System.nanoTime()}")
                            part.provider().copyAndClose(file.writeChannel())
                            report.appendLine(
                                "file ${part.name}: ${part.originalFileName}, " +
                                    "${part.contentType}, ${file.length()} bytes"
                            )
                        }
                        else -> {}
                    }
                    part.release()
                }
                call.respondText(report.toString())
            }
        }
    }.start(wait = false)
    val port = runBlocking { server.engine.resolvedConnectors().first().port }

    runBlocking {
        HttpClient(CIO).use { client ->
            val response = client.submitFormWithBinaryData(
                url = "http://localhost:$port/upload",
                formData = formData {
                    append("title", "Holiday photos")
                    append("photo", ByteArray(2048) { it.toByte() }, Headers.build {
                        append(HttpHeaders.ContentType, "image/jpeg")
                        append(HttpHeaders.ContentDisposition, "filename=\"beach.jpg\"")
                    })
                    append("notes", "Day one\nDay two".toByteArray(), Headers.build {
                        append(HttpHeaders.ContentType, "text/plain")
                        append(HttpHeaders.ContentDisposition, "filename=\"notes.txt\"")
                    })
                }
            )
            println(response.status)
            print(response.bodyAsText())
        }
    }
    server.stop(100, 500)
    uploadDir.deleteRecursively()
}

Output:

200 OK
field title = Holiday photos
file photo: beach.jpg, image/jpeg, 2048 bytes
file notes: notes.txt, text/plain, 15 bytes

How it works:

Because fields and files arrive in the client's order, a field sent after a file isn't known yet while you save the file. If you need metadata (an album id, say) to decide where a file goes, ask clients to send those fields first, or save files to a temporary location and move them at the end.

Sending files with the Ktor client

submitFormWithBinaryData builds the multipart body from a formData { } block. That's what the client half of the example above does:

A ByteArray has to be in memory. For a large file on disk, pass a ChannelProvider instead. It opens the file only when the request is sent and reads it chunk by chunk. onUpload reports progress:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.onUpload
import io.ktor.client.request.forms.ChannelProvider
import io.ktor.client.request.forms.formData
import io.ktor.client.request.forms.submitFormWithBinaryData
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.content.PartData
import io.ktor.http.content.forEachPart
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.receiveMultipart
import io.ktor.server.response.respondText
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import io.ktor.util.cio.readChannel
import io.ktor.utils.io.discard
import kotlinx.coroutines.runBlocking
import java.io.File
import java.io.RandomAccessFile

fun main() {
    // a 30 MB file to upload
    val bigFile = File.createTempFile("video", ".mp4")
    RandomAccessFile(bigFile, "rw").use { it.setLength(30L * 1024 * 1024) }

    val server = embeddedServer(Netty, port = 0) {
        routing {
            post("/upload") {
                var received = 0L
                // raise the 50 MB default per-part limit for this route
                call.receiveMultipart(formFieldLimit = 100L * 1024 * 1024).forEachPart { part ->
                    if (part is PartData.FileItem) {
                        received += part.provider().discard() // a real server would store it
                    }
                    part.release()
                }
                call.respondText("server received $received bytes")
            }
        }
    }.start(wait = false)
    val port = runBlocking { server.engine.resolvedConnectors().first().port }

    runBlocking {
        HttpClient(CIO).use { client ->
            var nextReport = 0
            val response = client.submitFormWithBinaryData(
                url = "http://localhost:$port/upload",
                formData = formData {
                    // the file is read lazily, chunk by chunk, while the request is sent
                    append("video", ChannelProvider(bigFile.length()) { bigFile.readChannel() }, Headers.build {
                        append(HttpHeaders.ContentType, "video/mp4")
                        append(HttpHeaders.ContentDisposition, "filename=\"${bigFile.name}\"")
                    })
                }
            ) {
                onUpload { sent, total ->
                    val percent = if (total != null && total > 0) (sent * 100 / total).toInt() else 0
                    if (percent >= nextReport) {
                        println("sent $sent of $total bytes ($percent%)")
                        nextReport += 25
                    }
                }
            }
            println(response.bodyAsText())
        }
    }
    server.stop(100, 500)
    bigFile.delete()
}

Output:

sent 214 of 31457572 bytes (0%)
sent 7864534 of 31457572 bytes (25%)
sent 15728854 of 31457572 bytes (50%)
sent 23597270 of 31457572 bytes (75%)
sent 31457572 of 31457572 bytes (100%)
server received 31457280 bytes

Things to note:

Limits and validation

An upload endpoint accepts arbitrary bytes from anyone who can reach it. Before you put one in production, decide:

The next example does all four. It accepts up to three images, at most 512 KB each and 1 MB per request, and saves them under random names. If any file is rejected, the files already saved from that request are deleted:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.forms.formData
import io.ktor.client.request.forms.submitFormWithBinaryData
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.content.PartData
import io.ktor.http.content.forEachPart
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.PayloadTooLargeException
import io.ktor.server.plugins.bodylimit.RequestBodyLimit
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.request.receiveMultipart
import io.ktor.server.response.respondText
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.server.routing.routing
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.UUID
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createTempDirectory
import kotlin.io.path.deleteIfExists
import kotlin.io.path.deleteRecursively
import kotlin.io.path.fileSize
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.name
import kotlin.io.path.outputStream

const val MAX_FILE_SIZE = 512 * 1024L     // per file
const val MAX_REQUEST_SIZE = 1024 * 1024L // whole request
const val MAX_FILES = 3

class UploadRejected(val status: HttpStatusCode, message: String) : Exception(message)

// Copies the channel to a file, failing as soon as more than `limit` bytes arrive.
suspend fun ByteReadChannel.copyToFile(target: Path, limit: Long): Long {
    val buffer = ByteArray(8192)
    var total = 0L
    target.outputStream().use { out ->
        while (true) {
            val n = readAvailable(buffer)
            if (n == -1) break
            total += n
            if (total > limit) throw PayloadTooLargeException(limit)
            withContext(Dispatchers.IO) { out.write(buffer, 0, n) }
        }
    }
    return total
}

// Decide the type from the first bytes of the content, not from the
// file name or the Content-Type header, which the client controls.
fun sniffImageType(file: Path): String? {
    val head = ByteArray(8)
    val n = Files.newInputStream(file).use { it.readNBytes(head, 0, head.size) }
    fun startsWith(vararg sig: Int) =
        n >= sig.size && sig.indices.all { head[it] == sig[it].toByte() }
    return when {
        startsWith(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) -> "png"
        startsWith(0xFF, 0xD8, 0xFF) -> "jpg"
        startsWith(0x47, 0x49, 0x46, 0x38) -> "gif"
        else -> null
    }
}

// The original name is only for display: strip any path and odd characters.
fun displayName(original: String?): String {
    val base = original.orEmpty().substringAfterLast('/').substringAfterLast('\\')
    val clean = base.filter { it.isLetterOrDigit() || it in "._- " }.trim('.', ' ')
    return clean.take(100).ifEmpty { "unnamed" }
}

@OptIn(ExperimentalPathApi::class)
fun main() {
    val uploadDir = createTempDirectory("uploads")

    val server = embeddedServer(Netty, port = 0) {
        install(StatusPages) {
            exception<UploadRejected> { call, e ->
                call.respondText(e.message!!, status = e.status)
            }
            exception<PayloadTooLargeException> { call, e ->
                call.respondText(e.message!!, status = HttpStatusCode.PayloadTooLarge)
            }
        }
        routing {
            route("/upload") {
                install(RequestBodyLimit) { bodyLimit { MAX_REQUEST_SIZE } }
                post {
                    val saved = mutableListOf<String>()
                    val stored = mutableListOf<Path>()
                    var fileCount = 0
                    try {
                        call.receiveMultipart().forEachPart { part ->
                            try {
                                if (part is PartData.FileItem) {
                                    if (++fileCount > MAX_FILES) {
                                        throw UploadRejected(HttpStatusCode.BadRequest, "at most $MAX_FILES files")
                                    }
                                    val name = displayName(part.originalFileName)
                                    val tmp = Files.createTempFile(uploadDir, "partial-", ".tmp")
                                    try {
                                        val size = part.provider().copyToFile(tmp, MAX_FILE_SIZE)
                                        val ext = sniffImageType(tmp) ?: throw UploadRejected(
                                            HttpStatusCode.UnsupportedMediaType,
                                            "$name is not a PNG, JPEG or GIF"
                                        )
                                        val target = uploadDir.resolve("${UUID.randomUUID()}.$ext")
                                        Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE)
                                        stored.add(target)
                                        saved += "$name ($size bytes, $ext)"
                                    } finally {
                                        tmp.deleteIfExists()
                                    }
                                }
                            } finally {
                                part.release()
                            }
                        }
                    } catch (e: Throwable) {
                        stored.forEach { it.deleteIfExists() } // all or nothing
                        throw e
                    }
                    if (saved.isEmpty()) throw UploadRejected(HttpStatusCode.BadRequest, "no files")
                    call.respondText("saved " + saved.joinToString())
                }
            }
        }
    }.start(wait = false)
    val port = runBlocking { server.engine.resolvedConnectors().first().port }

    val png = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) + ByteArray(1000)
    val exe = "MZ".toByteArray() + ByteArray(1000)

    runBlocking {
        HttpClient(CIO).use { client ->
            suspend fun upload(label: String, files: List<Pair<String, ByteArray>>) {
                val response = client.submitFormWithBinaryData(
                    "http://localhost:$port/upload",
                    formData {
                        for ((name, bytes) in files) {
                            append("file", bytes, Headers.build {
                                append(HttpHeaders.ContentType, "image/png")
                                append(HttpHeaders.ContentDisposition, "filename=\"$name\"")
                            })
                        }
                    }
                )
                println("$label -> ${response.status.value} ${response.bodyAsText()}")
            }
            val big = png + ByteArray(400_000)
            upload("ok", listOf("cat.png" to png))
            upload("path", listOf("../../etc/cron.d/evil.png" to png))
            upload("fake png", listOf("photo.png" to exe))
            upload("big file", listOf("huge.png" to png + ByteArray(600_000)))
            upload("big request", listOf("a.png" to big, "b.png" to big, "c.png" to big))
            upload("too many", List(4) { "p$it.png" to png })
        }
    }
    val names = uploadDir.listDirectoryEntries().map { "${it.name} ${it.fileSize()}" }
    println("on disk:\n" + names.sorted().joinToString("\n"))
    server.stop(100, 500)
    uploadDir.deleteRecursively()
}

Output (the names are random):

ok -> 200 saved cat.png (1008 bytes, png)
path -> 200 saved evil.png (1008 bytes, png)
fake png -> 415 photo.png is not a PNG, JPEG or GIF
big file -> 413 Request is larger than the limit of 524288 bytes
big request -> 413 Request is larger than the limit of 1048576 bytes
too many -> 400 at most 3 files
on disk:
46ff8bd4-2d8c-42cb-96c7-aa21e16613b0.png 1008
d70fa3fd-0d94-48d6-b9b3-513f35e83f93.png 1008

What each check does:

A few more things to consider:

Raw uploads with PUT

When a client sends a single file, multipart framing isn't needed. The body is the file. On the server, call.receiveChannel() gives you the body as a ByteReadChannel, and you can process it as it streams in. This example computes a SHA-256 checksum while writing the file, and compares it with the one the client sent:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.header
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.contentLength
import io.ktor.server.request.header
import io.ktor.server.request.receiveChannel
import io.ktor.server.response.respondText
import io.ktor.server.routing.put
import io.ktor.server.routing.routing
import io.ktor.util.cio.readChannel
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.io.File
import java.security.MessageDigest
import kotlin.io.path.createTempDirectory
import kotlin.random.Random

fun sha256(file: File): String {
    val md = MessageDigest.getInstance("SHA-256")
    file.inputStream().use { input ->
        val buf = ByteArray(8192)
        while (true) {
            val n = input.read(buf)
            if (n == -1) break
            md.update(buf, 0, n)
        }
    }
    return md.digest().toHexString()
}

fun main() {
    val storage = createTempDirectory("storage").toFile()
    val source = File.createTempFile("backup", ".tar.gz")
    source.writeBytes(Random(42).nextBytes(5_000_000))

    val server = embeddedServer(Netty, port = 0) {
        routing {
            put("/files/{name}") {
                val name = call.parameters["name"]!!
                if (!name.matches(Regex("[A-Za-z0-9._-]{1,100}")) || name.startsWith(".")) {
                    return@put call.respondText("bad name", status = HttpStatusCode.BadRequest)
                }
                val expected = call.request.header("X-Checksum-SHA256")
                val target = File(storage, name)
                val tmp = File(storage, "$name.part")
                val md = MessageDigest.getInstance("SHA-256")
                val body = call.receiveChannel()
                val buf = ByteArray(64 * 1024)
                var size = 0L
                tmp.outputStream().use { out ->
                    while (true) {
                        val n = body.readAvailable(buf)
                        if (n == -1) break
                        md.update(buf, 0, n) // hash while streaming, no second pass
                        withContext(Dispatchers.IO) { out.write(buf, 0, n) }
                        size += n
                    }
                }
                val actual = md.digest().toHexString()
                if (expected != null && !expected.equals(actual, ignoreCase = true)) {
                    tmp.delete()
                    return@put call.respondText("checksum mismatch", status = HttpStatusCode.UnprocessableEntity)
                }
                tmp.renameTo(target)
                val length = call.request.contentLength()
                call.respondText(
                    "stored $name: $size bytes (Content-Length: $length), sha256 ${actual.take(16)}...",
                    status = HttpStatusCode.Created
                )
            }
        }
    }.start(wait = false)
    val port = runBlocking { server.engine.resolvedConnectors().first().port }

    runBlocking {
        HttpClient(CIO).use { client ->
            val checksum = sha256(source)
            val ok = client.put("http://localhost:$port/files/backup.tar.gz") {
                contentType(ContentType.Application.OctetStream)
                header("X-Checksum-SHA256", checksum)
                setBody(source.readChannel()) // streamed, not loaded into memory
            }
            println("${ok.status.value} ${ok.bodyAsText()}")

            val bad = client.put("http://localhost:$port/files/other.bin") {
                header("X-Checksum-SHA256", "00".repeat(32))
                setBody(source.readChannel())
            }
            println("${bad.status.value} ${bad.bodyAsText()}")
        }
    }
    println("on disk: " + storage.list()!!.sorted())
    server.stop(100, 500)
    storage.deleteRecursively()
    source.delete()
}

Output:

201 stored backup.tar.gz: 5000000 bytes (Content-Length: null), sha256 d6069a6ac453e7e1...
422 checksum mismatch
on disk: [backup.tar.gz]

Things to note:

Multipart with java.net.http

The JDK's HttpClient (see HTTP client) has no multipart support, but the format is simple enough to build yourself. BodyPublishers.concat() (JDK 16+) chains publishers, so the file is still streamed from disk with ofFile():

import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpRequest.BodyPublisher
import java.net.http.HttpRequest.BodyPublishers
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.Path
import java.util.UUID

class MultipartBody {
    val boundary = "----kotlin-" + UUID.randomUUID().toString().replace("-", "")
    private val parts = mutableListOf<BodyPublisher>()

    fun field(name: String, value: String) {
        parts += BodyPublishers.ofString(
            "--$boundary\r\n" +
                "Content-Disposition: form-data; name=\"$name\"\r\n\r\n" +
                "$value\r\n"
        )
    }

    fun file(name: String, path: Path, contentType: String) {
        parts += BodyPublishers.ofString(
            "--$boundary\r\n" +
                "Content-Disposition: form-data; name=\"$name\"; filename=\"${path.fileName}\"\r\n" +
                "Content-Type: $contentType\r\n\r\n"
        )
        parts += BodyPublishers.ofFile(path) // streamed from disk when the request is sent
        parts += BodyPublishers.ofString("\r\n")
    }

    fun build(): BodyPublisher =
        BodyPublishers.concat(*parts.toTypedArray(), BodyPublishers.ofString("--$boundary--\r\n"))

    val contentType get() = "multipart/form-data; boundary=$boundary"
}

fun main() {
    // a tiny server that echoes back what it received
    val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
    server.createContext("/upload") { ex ->
        val body = ex.requestBody.readAllBytes()
        val reply = "Content-Type: ${ex.requestHeaders.getFirst("Content-Type")}\n" +
            "Content-Length: ${ex.requestHeaders.getFirst("Content-Length")}\n\n" +
            String(body)
        val bytes = reply.toByteArray()
        ex.sendResponseHeaders(200, bytes.size.toLong())
        ex.responseBody.use { it.write(bytes) }
    }
    server.start()

    val dir = Files.createTempDirectory("upload")
    val file = dir.resolve("report.csv")
    Files.writeString(file, "id,amount\n1,9.99\n2,24.50\n")

    val multipart = MultipartBody().apply {
        field("year", "2026")
        file("report", file, "text/csv")
    }
    val request = HttpRequest.newBuilder(URI("http://127.0.0.1:${server.address.port}/upload"))
        .header("Content-Type", multipart.contentType)
        .POST(multipart.build())
        .build()

    HttpClient.newHttpClient().use { client ->
        val response = client.send(request, HttpResponse.BodyHandlers.ofString())
        println(response.statusCode())
        print(response.body())
    }
    server.stop(0)
    Files.delete(file)
    Files.delete(dir)
}

Output:

200
Content-Type: multipart/form-data; boundary=----kotlin-035bb45bbcfb41ec89c7853ecd6dbf7a
Content-Length: 319

------kotlin-035bb45bbcfb41ec89c7853ecd6dbf7a
Content-Disposition: form-data; name="year"

2026
------kotlin-035bb45bbcfb41ec89c7853ecd6dbf7a
Content-Disposition: form-data; name="report"; filename="report.csv"
Content-Type: text/csv

id,amount
1,9.99
2,24.50

------kotlin-035bb45bbcfb41ec89c7853ecd6dbf7a--

The server here is the JDK's built-in com.sun.net.httpserver.HttpServer, which echoes the raw body. It shows exactly what the client sent:

With OkHttp, MultipartBody.Builder does the same job, and RequestBody.asRequestBody() streams a file.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents