ktor 客户端发布多部分/表单数据

abo*_*bus 8 kotlin telegram ktor

如何使用 ktor 客户端将文件作为多部分/表单数据发布?我想将它用于电报机器人 API“发送文档”。我需要获得与curl命令相同的结果

curl -F document=@"path/to/some.file" https://api.telegram.org/bot<token>/sendDocument?chat_id=<chat_id>
Run Code Online (Sandbox Code Playgroud)

Ale*_*man 6

您可以使用submitFormWithBinaryData方法发送mutlipart/form-data请求。这是一个解决方案:

val client = HttpClient(Apache) {}

val file = File("path/to/some.file")
val chatId = "123"

client.submitFormWithBinaryData(
    url = "https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId",
    formData = formData {
        append("document", file.readBytes(), Headers.build {
            append(HttpHeaders.ContentDisposition, "filename=${file.name}")
        })
    }
)
Run Code Online (Sandbox Code Playgroud)