You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Apache Camel REST端点提取HTML页面上传txt文件的内容

解决步骤

  1. 首先在REST路由配置中添加multipart支持,声明接收的内容类型为multipart/form-data,可选添加MIME多部分解析:
rest("/uploadFile").post("/")
    .consumes("multipart/form-data") // 声明接收表单上传格式
    .param("file").endParam()
    .unmarshal().mimeMultipart() // 启用多部分内容自动解析
    .to("bean:BeanName?method=converterMethod(Exchange)"); 
  1. 在Bean的处理方法中直接提取文件内容,有两种常用方式:

方式1:从附件中提取(推荐)

Camel解析multipart请求后,上传的文件会作为附件存储在Exchange中,直接按表单字段名读取即可:

import org.apache.camel.Attachment;
import org.apache.camel.Exchange;

public class BeanName {
    public void converterMethod(Exchange exchange) throws Exception {
        // 对应表单中input的name属性值"file"
        Attachment fileAttachment = exchange.getIn().getAttachment("file");
        // 转换附件流为字符串,即可得到纯净的文本内容
        String txtContent = exchange.getContext().getTypeConverter()
                .convertTo(String.class, fileAttachment.getInputStream());
        // 后续处理txtContent即可
    }
}

方式2:从解析后的Map中提取

启用mimeMultipart解码后,消息Body会被转换为Map<String, Object>,key对应表单字段名,直接取值即可:

import org.apache.camel.Exchange;
import java.util.Map;

public class BeanName {
    public void converterMethod(Exchange exchange) {
        Map<String, Object> formData = exchange.getIn().getBody(Map.class);
        // 按字段名取对应内容,如果你要取示例中的Hello内容,对应字段名是"test.txt"
        String txtContent = (String) formData.get("test.txt");
        // 取上传的文件内容对应字段名是"file"
        Object fileContent = formData.get("file");
    }
}

注意事项

  • Camel 3.x及以上版本需要额外引入camel-attachments依赖才能使用附件相关能力。
  • 如果你使用Spring Boot集成,避免Camel和Spring自带的Multipart解析器冲突,可以选择关闭Spring的Multipart自动配置,或只使用其中一套解析逻辑。

内容的提问来源于stack exchange,提问作者Akshay Sakunde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:30:00