File uploads
suggest changeFiles reach a server in one of two ways:
multipart/form-data: what a browser sends for an HTML form with<input type="file">. One request carries several parts, each with its own headers. Parts can be files or plain form fields.- Raw body: the request body is the file itself, usually sent with
PUTorPOSTandContent-Type: application/octet-stream. APIs and command-line tools often do this, and so do object stores like S3.
This article shows both directions with Ktor:
- receiving multipart uploads on the server and streaming them to disk
- sending files from the Ktor client, with upload progress
- limits on size and file count, sniffing the file type, and safe file names
- raw streaming uploads with a checksum
- building a multipart request by hand with the JDK's
java.net.http
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:
PartData.FormItemis an ordinary field.part.valueis its text.PartData.FileItemis a file.part.originalFileNameandpart.contentTypecome from the part's headers, andpart.provider()returns aByteReadChannelwith the content.copyAndClose(file.writeChannel())streams the part to disk. The file is never held in memory, so a 2 GB upload uses no more heap than a 2 KB one.- Parts arrive one after another on the same connection. Read each part fully, or let
release()skip it, before the next one can be parsed. You can't keep aFileItemand read it later. - Call
part.release()when you're done with a part. It frees the resources held by the part. (dispose()from older Ktor versions is deprecated.) PartData.BinaryItemandPartData.BinaryChannelItemare other part types, used mostly by the client. Theelsebranch ignores them.
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:
append("title", "Holiday photos")adds a text field.append("photo", bytes, headers)adds a file part. TheContent-Dispositionheader withfilename=is what makes the server see it as aFileItem. Without it, the part arrives as aFormItem.- Ktor generates the boundary and the
Content-Typeheader for you.
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:
ChannelProvider(size) { ... }tells Ktor the part's size, so it can compute the whole request'sContent-Length(here 292 bytes of multipart headers plus the 30 MB file). With a known length,onUploadgets a non-nulltotal. Without a size, Ktor sends the body chunked andtotalisnull.onUploadis called many times as data is written to the socket. Throttle what you do in it, for example update a progress bar only when the percentage changes.onDownloadis the matching hook for response bodies.- On the server,
receiveMultipart()limits each part to 50 MB by default. Larger parts fail with anIOException. Raise the limit for one call withreceiveMultipart(formFieldLimit = ...), or for the whole server with theio.ktor.server.request.formFieldLimitsystem property.
Limits and validation
An upload endpoint accepts arbitrary bytes from anyone who can reach it. Before you put one in production, decide:
- How big? Limit the whole request and each file, or one client can fill your disk.
- How many files? Many tiny files can be as expensive as one large one.
- What type? The file name and the part's
Content-Typeare chosen by the client. Look at the content. - Where does it go? Never build a path from the client's file name.
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:
RequestBodyLimit(fromktor-server-body-limit) is installed only on the/uploadroute. IfContent-Lengthis larger than the limit, it rejects the request before reading the body. If the client doesn't send a length (chunked encoding), it counts bytes as they're read. Either way it throwsPayloadTooLargeException, which becomes413 Payload Too Large. The "big request" case is rejected this way.- Per-file limit:
copyToFilecounts bytes while it copies and stops as soon as the file is too big, without first reading the whole part. This is the "big file" case: the request is under 1 MB, but one file is over 512 KB.formFieldLimitwould also stop it, but with a genericIOException. - File count: the counter rejects the fourth file. The client sees a
400with a clear message instead of a timeout or a crash. - Content sniffing:
sniffImageTypechecks the "magic bytes" at the start of the file. The fake PNG starts withMZ, the header of a Windows executable, so it's refused with415 Unsupported Media Type, even though its name andContent-Typesay PNG. For a wider range of formats use a library such as Apache Tika, and for images also check the dimensions before decoding them (see Images). - Storage names: the file is stored as
<uuid>.<detected extension>, never under the client's name. The upload named../../etc/cron.d/evil.pngwould escape the upload directory if the code usedFile(uploadDir, originalFileName).displayName()keeps a cleaned-up name to show to users. Store it in your database next to the UUID. - Atomic save: each file is first written to a
partial-*.tmpfile and moved into place only after it passes all checks. Other code never sees a half-written or unchecked file, and thefinallyblock deletes the temporary file on failure. - All or nothing: the outer
try/catchdeletes files already saved when a later part fails. Without it, the "too many" request would leave three files on disk even though the client got an error.
A few more things to consider:
- Store uploads outside the web root. If uploaded files can be served back by a static file handler, someone will upload an
.htmlor.svgfile with a script in it. When you serve uploads, set theContent-Typeyourself from the sniffed type, and addContent-Disposition: attachmentandX-Content-Type-Options: nosniff(see HTTP headers). - Archives and images can expand. A small ZIP file or PNG can decompress to gigabytes. Limit what you extract or decode, not just what you receive (see ZIP archives).
- Require authentication on upload endpoints (see Authentication), and rate-limit them.
- Uploads take time. Make sure the server's and any proxy's request timeouts allow for large files on slow connections. Nginx, for example, rejects bodies over 1 MB unless you raise
client_max_body_size.
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:
setBody(file.readChannel())streams the file. AByteReadChannelhas no length, so the client usesTransfer-Encoding: chunked, and the server seesContent-Length: null. This is also why you can't rely onContent-Lengthalone for size limits.- The name comes from the URL, so it's checked against a strict pattern. A name like
..or one with/is rejected. The checksum header is a convention of this example. S3, for instance, usesx-amz-checksum-sha256with a base64 value. - The data is hashed during the copy, so the server reads the body only once. When the checksum doesn't match, the
.partfile is deleted and the stored file is never created. - A raw
PUTis easy to make resumable: the client can ask how many bytes the server has and send the rest with aContent-Rangeheader. For that, look at protocols like tus instead of designing your own.
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:
- The boundary must not appear in the content. A random UUID makes that practically impossible.
- Every part starts with
--+ boundary, and the body ends with--+ boundary +--. Lines end with\r\n, and an empty line separates part headers from content. BodyPublishers.ofFile()knows the file size, soconcat()can compute theContent-Length(319 bytes here).- This simple builder doesn't escape quotes or line breaks in field and file names. If names can contain them, percent-encode them or replace them before you put them in the header.
With OkHttp, MultipartBody.Builder does the same job, and RequestBody.asRequestBody() streams a file.
Tips
- Stream, don't buffer. Avoid
receive<ByteArray>(),readBytes()ortoByteArray()for uploads. Copy channels to files and keep memory use flat. - Limit everything: request size, file size, file count and field size. Answer with
413for size and415for type, and include a short message. - Never trust the client's file name or
Content-Type. Generate your own names, detect the type from the content, and keep the original name only as data. - Write to a temporary file, then move it into place, and clean up partial files on every error path.
Files.movewithATOMIC_MOVEworks when both paths are on the same file system (see Temporary files). - Release every part. Use
try/finallyaround the code that handles a part, sopart.release()runs even when you throw. - Give
ChannelProvidera size on the client when you know it, so the request has aContent-Lengthand progress reporting has a total. - For big files in the cloud, let the client upload directly to object storage with a pre-signed URL. Your server only signs the URL and gets notified when the upload finishes, instead of passing gigabytes through itself.