我正在尝试从客户端向我的服务器发出一个get请求。我的服务器响应具有图像/png内容类型。我怎样才能从我的kotlin密码中接收到这个图像?
发布于 2022-04-23 15:11:18
您将希望从Ktor服务器提供静态内容:https://ktor.io/docs/serving-static-content.html
创建一个静态文件夹,然后将图像放在其中:
static("/") {
staticRootFolder = File("files")
}
设置好之后,您可以在该文件夹中引用文件。如果您也想要子文件夹中的文件,可以添加一个额外的files(".")
行:
static("/") {
staticRootFolder = File("files")
files(".")
}
发布于 2022-04-24 02:57:27
您不仅可以下载图像,还可以下载任何其他文件。
像通常一样创建ktor-client
。
val client = HttpClient(OkHttp) {
install(ContentNegotiation) {
json(Json { isLenient = true; ignoreUnknownKeys = true })
}
}
要使用此client
下载文件,请使用bodyAsChannel()
读取response
,后者将响应读入为ByteReadChannel
。使用copyAsChannel()
在磁盘上写入数据,传递目标的ByteWriteChannel
。
GlobalScope.launch(Dispatchers.IO) {
val url = Url("FILE_DOWNLOAD_LINK")
val file = File(url.pathSegments.last())
client.get(url).bodyAsChannel().copyAndClose(file.writeChannel())
println("Finished downloading..")
}
https://stackoverflow.com/questions/71980361
复制相似问题