繁体   English   中英

如何从 curl 或 postman 或 swagger Micronaut 传递值 @Body MultipartBody

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

我在 Micronaut 中有一个简单的以下 post 方法,它将图像发送到 controller,如下所示

@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";
    }
}

如何将文件的值从 postman、curl 或 Z5DB89E74732F81A7EAF61C76 传递给 controller?

我尝试了以下事情

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

在此处输入图像描述

我收到错误,因为Required Body [file] not specified 我们如何传递价值?

更改post()方法的签名以使用@Part而不是@Body并直接使用byte数组而不是MultipartBody 您还可以在@Part注释中定义部件名称,在您的情况下是文件

它看起来像这样:

@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);
    }

}

例如 curl 调用:

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

...回应:

Received: Some dummy data in text file.

所以问题不在于您的 curl 命令或从 Postman 调用,而是在 controller 实现中。


这是该操作的声明性客户端示例:

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

该客户端可以这样使用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM