You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ktor Client以multipart/form-data格式上传文件调用Telegram Bot发送文档接口

Ktor Client 实现调用Telegram Bot API sendDocument接口发送文件

你需要实现等效的curl命令如下:

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

1. 前置依赖配置

首先需要在项目中引入Ktor Client相关依赖,以下为Gradle Kotlin DSL配置示例:

dependencies {
    // Ktor Client核心库
    implementation("io.ktor:ktor-client-core:2.3.3")
    // 可选用OkHttp引擎,也可替换为CIO等其他引擎
    implementation("io.ktor:ktor-client-okhttp:2.3.3")
    // 可选:如果需要解析接口返回的JSON结果,可引入内容协商和序列化依赖
    implementation("io.ktor:ktor-client-content-negotiation:2.3.3")
    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.3")
}

2. 核心实现代码

以下代码完全实现上述curl的请求逻辑,采用multipart/form-data格式提交文件,chat_id放在URL请求参数中:

import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.request.forms.*
import io.ktor.client.statement.*
import io.ktor.http.*
import java.io.File

suspend fun sendTelegramDocument(
    botToken: String,
    chatId: String,
    filePath: String
): HttpResponse {
    val client = HttpClient(OkHttp) {
        // 不需要解析返回JSON可删除以下内容协商配置
        // install(ContentNegotiation) {
        //     json()
        // }
    }

    return client.use {
        it.post("https://api.telegram.org/bot$botToken/sendDocument") {
            // 对应curl中chat_id的query参数配置
            parameter("chat_id", chatId)
            // 构造multipart/form-data请求体
            setBody(MultiPartFormDataContent(
                formData {
                    // 对应curl中的document=@文件参数
                    append(
                        key = "document",
                        value = File(filePath).readBytes(),
                        headers = Headers.build {
                            append(HttpHeaders.ContentDisposition, "form-data; name=\"document\"; filename=\"${File(filePath).name}\"")
                        }
                    )
                }
            ))
        }
    }
}

3. 注意事项

  • 以上代码适配Ktor 2.x版本,如果使用Ktor 1.x版本需要调整对应API
  • 大文件上传不要直接使用readBytes()读取,避免内存溢出,可改为流式上传,替换append的value参数即可:
    value = ChannelProvider { File(filePath).readChannel() }
    
  • 网络环境无法直接访问Telegram API时,需要自行给HttpClient配置代理规则

内容的提问来源于stack exchange,提问作者abobus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:45:07