Apache Camel 多部分路由
我正在尝试通过 Apache Camel 将文件路由到 HTTP 文件上传 API.但是我遇到了以下异常
I'm trying to route a file to HTTP file upload API via Apache Camel. But I'm getting following exception
org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: org.apache.http.entity.mime.MultipartFormEntity@71ef4d4f of type: org.apache.http.entity.mime.MultipartFormEntity on: org.apache.camel.component.file.GenericFileMessage@7e693963. Caused by: No type converter available to convert from type: org.apache.http.entity.mime.MultipartFormEntity to the required type: java.io.InputStream with value org.apache.http.entity.mime.MultipartFormEntity@71ef4d4f. Exchange[org.apache.camel.component.file.GenericFileMessage@7e693963]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: org.apache.http.entity.mime.MultipartFormEntity to the required type: java.io.InputStream with value org.apache.http.entity.mime.MultipartFormEntity@71ef4d4f]
有人可以帮忙吗?以下是我迄今为止尝试过的
Can anyone help here? Following is what I tried so far
与 URL api/fileupload 映射的文件上传控制器方法需要 MultipartHttpServletRequest
My fileupload controller method mapped with the URL api/fileupload expects a MultipartHttpServletRequest
MyCamelRouter.java
MyCamelRouter.java
public class MyCamelRouter extends RouteBuilder {
@Override
public void configure() throws Exception {
from("file:C:/src")
.process(new MyProcessor())
.log("POST ${header.CamelFileName} to /upload")
.setHeader(Exchange.CONTENT_TYPE, constant("multipart/form-data"))
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.to("http:localhost:8080/sampleUploader/api/fileupload")
.log("HTTP response status: ${header.CamelHttpResponseCode}")
.log(LoggingLevel.DEBUG, "HTTP response body:\n${body}");
}
}
在 MyProcessor.java 中
and in MyProcessor.java
public class MyProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
File filetoUpload = exchange.getIn().getBody(File.class);
String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addTextBody("fileName", fileName);
entity.addBinaryBody("file", new File(filePath));
exchange.getOut().setBody(entity.build());
}
}
这个是我为此而遵循的链接(Scala DSL)
This is the link I followed for this(Scala DSL)
当它说你需要一个 InputStream 时,这个消息很清楚
The message is clear when it say that you need an InputStream
方法 build 返回一个 HttpEntity.
The method build returns an HttpEntity.
您可以尝试使用 getContent() 方法
You can try with the method getContent()
尝试改变你的:
exchange.getOut().setBody(entity.build());
到:
exchange.getOut().setBody(entity.build().getContent());
更新
发表评论后,您可以做的另一件事是:
After your comment the other thing you can do is:
ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.build().writeTo(out);
InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
exchange.getOut().setBody(inputStream);