nfont
nfont

Reputation: 99

Kotlin (Ktor) request class for multipart form data

I want to create a request class that collects all the parts (files and items) and validate it, something similar to the example I put (below) with the json requests.

REQUEST JSON SERIALIZABLE EXAMPLE CLASS

import kotlinx.serialization.Serializable

@Serializable
class CreateGroupRequest(
    val name: String,
    val description: String? = null,
    val visibility: String? = "PUBLIC"
)

HANDLE JSON REQUEST EXAMPLE

route("create") {
                post {
                    val request = call.receive<CreateGroupRequest>()
                    try {
                        //CODE
                        call.respond(HttpStatusCode.OK)
                    } catch (e: SharedDomainException) {
                        call.respond(HttpStatusCode(e.errorCode, e.errorMessage))
                    }
                }
            }

What I mean, for example, is that in this case I want to change it because the groups also has a profile photo that I want to upload or in other cases, posts domain has text, author and a multiple images.

I have read this stackOverflow post but I can't see how I can make a general class to read the multipart requests without having to duplicate code in each handler.

So, does anyone know how I can read the request multipart-form-data body in a shared class and validate it with kotlin/ktor?

Upvotes: 0

Views: 3305

Answers (1)

Aleksei Tirman
Aleksei Tirman

Reputation: 7079

In principle, you can use the ContentNegotiation and register a content converter for the multipart/form-data Content-type. In the convertForReceive method you can use CIOMultipartDataBase to parse multipart data and then deserialize it using kotlinx.serialization library. For deserialize method call you need to provide a decoder for the MultiPartData objects, which you need to implement.

The above approach will work but is very inefficient for parts with a large binary body because parts in an HTTP message go one after another so all of them will be eagerly read into memory.

Upvotes: 3

Related Questions