使用Ktor Client上传文件时遭遇java.net.ProtocolException异常求助
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

