Coyado
Coyado

Reputation: 13

KTOR - Unzip file in POST routing

I want to unzip a file zip sent within the body of a http query (content type: application/x-gzip) in Ktor (bloc rounting). I've tried this:

val zip_received=call.receiveStream() val incomingContent = GZIPInputStream(zip_received).toByteReadChannel()

But I got this error:

java.lang.IllegalStateException: Acquiring blocking primitives on this dispatcher is not allowed. Consider using async channel or doing withContext(Dispatchers.IO) { call.receive().use { ... } } instead.

I'm not able to write such function. Can I have some helps ?

Thanks

Upvotes: 0

Views: 780

Answers (1)

Aleksei Tirman
Aleksei Tirman

Reputation: 7079

You can use the following code to read GZip uncompressed request body as string:

import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.util.zip.GZIPInputStream

fun main(args: Array<String>) {
    embeddedServer(Netty, port = 9090) {
        routing {
            post("/") {
                withContext(Dispatchers.IO) {
                    call.receive<InputStream>().use { stream ->
                        val gzipStream = GZIPInputStream(stream)
                        val uncompressedBody = String(gzipStream.readAllBytes())
                        println(uncompressedBody)
                    }
                }
            }
        }
    }.start()
}

Upvotes: 1

Related Questions