Sujan Mandal
Sujan Mandal

Reputation: 3

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)
                    }
                }

Upvotes: 0

Views: 41

Answers (1)

Aleksei Tirman
Aleksei Tirman

Reputation: 7099

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()
            }
        }
    }
}

Upvotes: 1

Related Questions