Search code examples
javacurlpostmanmicronautmicronaut-client

How to pass the value @Body MultipartBody from curl or postman or swagger Micronaut


I have a simple below post method in Micronaut, which sends the image to the controller as shown below

@Controller("/product")
public class ProductController {

    @Post(consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.MULTIPART_FORM_DATA)
    public String post(@Body MultipartBody file){
        return "This is multipost";
    }
}

How can I pass the value of file to the controller from the postman, curl or swagger?

I tried the below things

curl --location --request POST 'http://localhost:8080/product' \
--form 'file=@"/Users/macbook/Downloads/anand 001.jpg"'

enter image description here

I get the error as Required Body [file] not specified. How do we pass the value?


Solution

  • Change signature of post() method to use @Part instead of @Body and use directly byte array instead of MultipartBody. You can also define the part name in @Part annotation, which is file in your case.

    It can look like this:

    @Controller("/products")
    public class ProductController {
    
        @Post(consumes = MediaType.MULTIPART_FORM_DATA)
        public String post(@Part("file") byte[] file) {
            return "Received: " + new String(file, StandardCharsets.UTF_8);
        }
    
    }
    

    And example curl call:

    curl -X POST 'http://localhost:8080/products' -F 'file=@/home/cgrim/tmp/test.txt'
    

    ... with response:

    Received: Some dummy data in text file.
    

    So the problem is not in your curl command or call from Postman but in the controller implementation.


    Here is an example of declarative client for that operation:

    @Client("/products")
    public interface ProductClient {
        @Post(produces = MULTIPART_FORM_DATA)
        HttpResponse<String> createProduct(@Body MultipartBody body);
    }
    

    And that client can be used like this:

    var requestBody = MultipartBody.builder()
        .addPart("file", file.getName(), TEXT_PLAIN_TYPE, file)
        .build();
    var response = client.createProduct(requestBody);