I need to save the request body to a file. Somethi...
# ktor
j
I need to save the request body to a file. Something like this:
Copy code
post {
   val targetChannel = FileOutputStream(Files.createTempFile("job-", ".json").toFile()).channel
   val originChannel = newChannel(call.receiveStream())

   originChannel.use {
       targetChannel.use {
            targetChannel.transferFrom(originChannel, 0L, 100000)
       }
    }
...
FileOutputStream, etc. are blocking calls. Is there a nonblocking API to write to files so I can use
receiveChannel()
?
a
You can use a
ByteWriteChannel
instance created from a file to copy bytes from input to output channel:
Copy code
post {
    val tmpFile = Files.createTempFile("job-", ".json").toFile()
    call.receiveChannel().copyTo(tmpFile.writeChannel())
}
👍 2
j
Very nice!
No need to close writeChannel or receiveChannel?
a
Better use
call.receiveChannel().copyAndClose(tmpFile.writeChannel())
instead
👍 1