1

I am trying to upload a file from Compose for Web form using Ktor.

My server code is based on the example found in the Ktor repo: https://github.com/ktorio/ktor-documentation/blob/2.1.0/codeSnippets/snippets/upload-file/src/main/kotlin/com/example/UploadFile.kt

       var fileDescription = ""
        var fileName = ""

        post("/upload") {
            val multipartData = call.receiveMultipart()

            multipartData.forEachPart { part ->
                when (part) {
                    is PartData.FormItem -> {
                        fileDescription = part.value
                    }

                    is PartData.FileItem -> {
                        fileName = part.originalFileName as String
                        var fileBytes = part.streamProvider().readBytes()
                        File("uploads/$fileName").writeBytes(fileBytes)
                    }

                    else -> {}
                }
            }

            call.respondText("$fileDescription is uploaded to 'uploads/$fileName'")
        }

My compose for web code looks like this:

        Div {
            Form(action = "/upload", attrs = {
                method(FormMethod.Post)
                encType(FormEncType.MultipartFormData)
            }) {
                FileInput {  }
                SubmitInput()
            }
 
        }

After selecting a file, the file input box does not change and when submitting the form the server is called correctly but the multipartData is empty. I have tried using an uncontrolled file input with type Input.File. Then I can see the file name in the file input after selecting it but the multipartData is still empty.

How do I upload the file?

HPage
  • 1,412
  • 20
  • 27

0 Answers0