繁体   English   中英

从 Camel 中的 multipart/form-data HTTP POST 请求中获取键值对

[英]Get key-value pairs from multipart/form-data HTTP POST request in Camel

我有一个端点设置,使用 Apache Camel 来接收多部分/表单数据 HTTP 请求。 本质上,我正在尝试提交一个数据文件和一个配置文件进行处理。 请求如下(由 Postman 生成):

POST /upload HTTP/1.1
Host: localhost:8900
Content-Length: 363
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"; filename="data-file.json"
Content-Type: application/json

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="config"; filename="config-file.json"
Content-Type: application/json

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW

我的路线是这样设置的:

@Component
public class FileReceiverRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {

        rest()
                .post("/upload")
                .consumes(MediaType.MULTIPART_FORM_DATA_VALUE)
                .bindingMode(RestBindingMode.off)
                .route().routeId("upload-route")
                .unmarshal().mimeMultipart()
                .setHeader(Exchange.FILE_NAME, () -> UUID.randomUUID().toString())
                .to("file:{{temp.input.files.dir}}")
                .process(configFileProcessor)
                // on to further processing
    }
}

还有我的配置文件处理器:

@Component
public class ConfigFileProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {
        Message message = exchange.getIn();
        AttachmentMessage attachmentMessage = exchange.getMessage(AttachmentMessage.class);
        Map<String, Attachment> attachmentObjects = attachmentMessage.getAttachmentObjects();

        // this fails - the key is instead the file name "config-file.json"
        Attachment configAttachment = attachmentObjects.get("config");
    }
}

我希望能够从表单数据中检索键值对并相应地处理数据和配置文件。 相反,我得到以下行为:

  • 表单中的第一个值(在本例中为data-file.json )被解析到 Camel 消息体中,并且密钥似乎被丢弃了。 条目的 rest 被解析为AttachmentMessage 此行为记录在此处https://stackoverflow.com/a/67566273/11248602
  • AttachmentMessage中的键不是来自表单数据请求的原始键,而是文件名(例如config-file.json

有没有办法将此请求解析为 map 或类似结构,以便可以访问所有原始键和值?

为了清楚起见,由于上面提出的解决方案似乎可行,因此需要更多解释(尽管它更像是一种解决方法而不是解决方案):

从...开始:

Map<String, Attachment> attachmentObjects = attachmentMessage.getAttachmentObjects();

可以浏览所有 map 条目,对于每个找到的Attachment object,使用getHeaderNames()检查附件标题,其中包括“内容处置”之一:

Content-Disposition: form-data; name="data"; filename="data-file.json"

最终可以对其进行解析以获取表单名称(本例中为“数据”)。

不是直截了当,但这显然有效......

暂无
暂无

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

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