kotlinhttpserverkotlin-multiplatformktor

How to get Mutlipart data as a file in ktor server efficiently?


Get file from multipart post request

Receive the file from PartData through streamProvider() not working

val fileName = part.originalFileName ?: "unknown"
val file = File(filename)
file.outputStream().use { output ->
                    part.streamProvider().use { input ->
                        input.copyTo(output)
                    }
                }

Solution

  • You can obtain a ByteReadChannel of a file part to read the data from by calling the FileItem.provider. This channel can then be used to copy the bytes to a ByteWriteChannel associated with the file. Here is an example:

    post {
        call.receiveMultipart().forEachPart { part ->
            if (part is PartData.FileItem) {
                val fileName = part.originalFileName ?: "unknown"
                val file = File(fileName)
                try {
                    part.provider().copyTo(file.writeChannel())
                } finally {
                    part.dispose()
                }
            }
        }
    }