kotlin - ktor 客户端发布多部分/表单数据
问题描述
如何将文件发布为 multipart/form-data 使用 ktor 客户端?我想将它用于电报机器人 API“发送文档”。我需要达到与 curl 命令相同的结果
curl -F document=@"path/to/some.file" https://api.telegram.org/bot<token>/sendDocument?chat_id=<chat_id>
解决方案
您可以使用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}")
})
}
)
推荐阅读
- python - Python:带有装饰器的函数的 __qualname__
- vba - 运行时错误“3075”访问
- ios - 如何在 iOS 模拟器中查看文档目录?
- elasticsearch - Elasticsearch:通配符搜索不适用于文本字段
- batch-file - 使用 ffprobe 的批处理脚本
- node.js - 如何通过匹配 ObjectId 字段从嵌套数组中删除对象
- docker - 在为 Microsoft SQL 存储过程构建 docker 映像时,我超出了最大深度
- python - 在 CreateView 中将 Django ForeignKey 显示为 Textarea
- jhipster - 为什么实体的 Angular 组件和模块类名称以应用程序基名称为前缀?
- rest - REST 检查资源是否存在,服务器端如何处理?