【发布时间】:2021-04-10 03:39:52
【问题描述】:
我有一个多平台项目,其中 api 代码在 iOS 和 Android 之间共享。
有“put” api 可以将本地音频文件作为二进制文件上传。
我已经创建了 httpclient 如下
val client = HttpClient {
defaultRequest {
url {
protocol = ServiceConfiguration.protocol
host = ServiceConfiguration.baseUrl
port = ServiceConfiguration.port
}
contentType(ContentType.Application.Json)
}
install(JsonFeature) {
val json = kotlinx.serialization.json.Json {
ignoreUnknownKeys = true
isLenient = true
}
serializer = KotlinxSerializer(json)
}
}
要将对象放入api中,我这样做如下
val response = ServiceRequest.client.put<String>(
body = File(path).readBytes()
)
它工作正常并将字节数组上传到后端。但我想将文件作为普通二进制文件上传,而不是字节数组。
为了更清楚,在 Postman mac 应用程序中,我们可以将文件上传为二进制文件。我需要做类似的事情。
当我签入 Ktor 时,它显示只有多部分表单数据可以作为二进制提交。但在我的情况下,它是 Put 请求。
请帮忙。
【问题讨论】:
-
你有没有尝试过类似的方法:suspend fun putMultipart(partData: List
) { httpClient.put ("url") { body = MultiPartFormDataContent(partData) } } -
这能回答你的问题吗? How to upload a file using Ktor client
-
我在这里找到了一个类似问题的答案 - stackoverflow.com/questions/60373937/…。
-
@ArtyomDegtyarev 感谢 cmets 的帮助,上面提到的 url 使用的是多部分或部分数据。但我只需要将文件作为二进制正文放入请求并上传。事实证明,使用 Ktor,我们无法做到这一点。我使用特定于平台的库来做到这一点。非常感谢
-
@KishorekumarEK 你是怎么得到这个 import File(path).readBytes() 是 kotlin multiplatform 中的 Java 文件吗?
标签: android kotlin kotlin-multiplatform ktor ktor-client