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

使用Ktor Client上传文件时遭遇java.net.ProtocolException异常求助

Solutions to java.net.ProtocolException: unexpected end of stream in Ktor Client File Upload

1. Correct the Content-Disposition Header

Your current header only specifies the filename but omits the name parameter that identifies the form field. Servers rely on this to parse multipart form data correctly. Update the header to include both:

append(HttpHeaders.ContentDisposition, "form-data; name=\"image\"; filename=\"ktor_logo.png\"")

2. Stream the File Directly Instead of Loading into Memory

Using readBytes() loads the entire file into memory, which can cause incorrect Content-Length calculation or memory issues for large files. Use the file object directly to stream content:

val response = httpClient.submitFormWithBinaryData(
    url = BASE_URL + "files/upload",
    formData = formData {
        append("image", file!!, Headers.build {
            append(HttpHeaders.ContentType, "image/png")
            append(HttpHeaders.ContentDisposition, "form-data; name=\"image\"; filename=\"ktor_logo.png\"")
        })
    }
)

3. Ensure the Multipart Plugin is Installed

Ktor Client requires the Multipart plugin to handle multipart form uploads. Add it to your HttpClient configuration:

val httpClient = HttpClient(OkHttp) {
    install(Multipart)
    // Other plugins (e.g., Logging, ContentNegotiation) go here
}

4. Validate File Access

Confirm the file exists and your application has read permissions. A missing or unreadable file can result in incomplete data transmission, triggering the end-of-stream error.

5. Check Server-Side Setup

If client-side fixes don't resolve the issue, verify the server is configured to accept multipart form data for the "image" field and supports the file size you're uploading.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 11:42:04