ktor客户端post多部分/form-data。

8

如何使用ktor客户端作为multipart/form-data发布文件?我想将其用于电报机器人API“发送文档”。 我需要实现与curl命令相同的结果。

curl -F document=@"path/to/some.file" https://api.telegram.org/bot<token>/sendDocument?chat_id=<chat_id>

这个回答解决了你的问题吗?使用ktor上传文件到Telegram Bot API - Phil Dukhov
请编辑问题,将其限制为具有足够细节以确定充分答案的特定问题。 - Community
2个回答

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

1
我看到很多类似这样的例子,但我希望没有人在生产中使用它们,因为如果涉及的文件大小是10MB,它将被加载到内存中并导致手机崩溃。 - TatiOverflow
你能告诉我如何在CommonMain中导入这个文件吗? - undefined

1

如果文件很大,您不会想将整个文件读入内存。相反,您可以流式传输上传。

val file = File("path/to/some.file")
client.submitFormWithBinaryData(
  url = "https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId",
  formData = formData {
    append(
      "document".quote(),
      InputProvider(file.length()) { file.inputStream().asInput() },
      Headers.build {
        append(HttpHeaders.ContentDisposition, "filename=${file.name.quote()}")
      }
    )
  }
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接