Hi, 2.0 question - with 1.X we’re able to upload a...
# ktor
n
Hi, 2.0 question - with 1.X we’re able to upload an image as follows:
Copy code
contentType(ContentType.Image.JPEG)
setBody(byteArray)
But in 2.0, I get a 500 error. Has anything changed with respect to this?
a
No. Just the
body
property is replaced with the
setBody
method.
n
Thanks! Apparently there's a bug with contentType being erased if you install the negotiation plugin, which makes the server refuse the request.
a
Could you please share a code snippet to reproduce this bug?
n
Copy code
val ktor = ktorClient
val image = imageFile.readBytes()
<http://ktor.post|ktor.post>(serverUrl) {
    contentType(ContentType.Image.JPEG)
    setBody(thumb)
}
It’s not really erased but it’s changed from
image/jpeg
which I explicitly set, to
application/octet-stream
. This didn’t happen in 1.X and also does not happen if I don’t apply the content negotiation plugin
I think application/octet-stream is the default for byte arrays, so since the plugin removes the header ( https://youtrack.jetbrains.com/issue/KTOR-3655 ), ktor ends up overriding it. I understand from KTOR-3655 that this is not considered a bug, but then how would I make this request? Currently using a separate client just for this endpoint
a
In the following code the
Content-Type
header with the value
application/octet-stream
is sent even when the
ContentNegotiation
plugin is installed:
Copy code
import io.ktor.client.*
import io.ktor.client.engine.apache.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*

suspend fun main() {
    val client = HttpClient(Apache) {
        install(ContentNegotiation) {
            json()
        }
    }

    val r = <http://client.post|client.post>("<https://httpbin.org/post>") {
        contentType(ContentType.Application.OctetStream)
        setBody(ByteArray(1024))
    }.bodyAsText()
    println(r)
}
n
Right so now if you change it to ContentType.Image.JPEG which is what my server expects, you should see that it gets overwritten (version 2.0.0-beta1)
a
I got it. Thank you.
👍 1
n
In case the underlying engine makes a difference, I’m using OkHttp on Android with default configuration
a
I don’t think so. I’ve reproduced it with the
Apache
engine.
I’ve created this issue to address the problem with ContentNegotiation plugin.
n
Thanks!