kotlinvert.xvertx-httpclientvert.x-webclient

I want send a filepart image with Vertx, I want replicate this case in code like Postman


PostmanExample

  fun sendFileToMatch(path:String){
    val client = WebClient.create(vertx);
    var form = MultipartForm.create()
      .binaryFileUpload("image","imageName" , path, "image/jpeg")

    client.post(8888, "localhost", "/search?")
      .putHeader("content-type", "multipart/form-data")
      .sendMultipartForm(form) { }
  }

when I run the code show bad request I have put exactly key "image" and send filepart image


Solution

  • TL;DR - your client code seems fine.

    The only suspicious part is the path itself, as you don't specify how exactly you get it in your code, and the fact that you didn't specify how you handle response from the server: you just do {} in your example

    Here is a fully working example for you to refer to, though:

            val vertx = Vertx.vertx()
    
        val router = Router.router(vertx)
    
        router.route().handler(BodyHandler.create());
        router.post("/search").handler {
            val uploads: Set<FileUpload> = it.fileUploads()
    
            uploads.forEach { upload ->
                println(upload.name()) // "image"
                println(upload.fileName()) // "imageName"
                println(upload.size()) // 42537
            }
    
            it.response().end("OK!")
        }
    
        vertx.createHttpServer().requestHandler(router)
                .listen(8888)
    
        // We read the PNG file from /resources
        val path = object {}.javaClass.getResource("5EWx9.png").path
        val form = MultipartForm.create()
                .binaryFileUpload("image","imageName" , path, "image/png")
    
        val client = WebClient.create(vertx);
        client.post(8888, "localhost", "/search?")
                .putHeader("content-type", "multipart/form-data")
                .sendMultipartForm(form) {
                    if (it.succeeded()) {
                        println(it.result().bodyAsString()) // "OK!"
                    }
                    else {
                        println(it.cause())
                    }
                }
    

    As the file to upload, I used the PostmanExample you've provided, which is a PNG image, which I put in the /resources directory of my project.