首页 > 解决方案 > KTOR - 在 POST 路由中解压缩文件

问题描述

我想解压缩在 Ktor(bloc rounting)中的 http 查询(内容类型:应用程序/x-gzip)的正文中发送的文件 zip。我试过这个:

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

但我得到了这个错误:

java.lang.IllegalStateException:不允许在此调度程序上获取阻塞原语。考虑使用异步通道或使用 withContext(Dispatchers.IO) { call.receive().use { ... } } 代替。

我无法编写这样的功能。我可以帮忙吗?

谢谢

标签: kotlinktor

解决方案


您可以使用以下代码将 GZip 未压缩请求正文读取为字符串:

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

推荐阅读