'How can I use camel http compponent to upload a file to an application running on apache tomcat server?
My requirement is to create a file-to-http route to upload a file from file component to an http server using http component. I aslo want to know how this camel http component works. Can we use camel http component to upload a file to http server.
Solution 1:[1]
This would depend on how you would want to submit the contents of the file. For example, let's say you have a number of lines in a CSV that need to be posted to an HTML form. You would likely build a route such as:
- From: Fetch a file from a given path
- To: Transform the data from the file into the appropriate HTTP headers (a simple POJO could do this well)
- To: Submit this via a POST over HTTP
If you want to upload the entire file, you're likely looking instead at an HTTP PUT that can also be performed by the component. You may want to set the file as an attachment to the Message then send it to the HTTP component using a PUT.
The component documentation provides a better overview at http://camel.apache.org/http4.html - but it seems like your biggest constraint will be what the file component consumer can do and what it should poll - see http://camel.apache.org/file2.html for details.
Solution 2:[2]
Depending on your HTTP server, you would have to take different approaches. If you have a given situation (Jetty server), you could use HTTP4 component to upload the file:
from("jetty:http://localhost:8081/upload?httpMethodRestrict=PUT")
.log("Uploaded ${body}");
from("file:src/data/jetty?delay=5000&noop=true")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.PUT))
.to("http4://localhost:8081/upload");
However, if the server accepts only multipart requests, you would have to get a bit more crafty, e.g. use something like this:
from("file:src/data/jersey?delay=5000&noop=true")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
MultipartEntityBuilder multipartEntityBuilder =
MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("username", username);
multipartEntityBuilder.addPart("password", password);
String filename = (String)
exchange.getIn().getHeader(Exchange.FILE_NAME);
File file = exchange.getIn().getBody(File.class);
multipartEntityBuilder.addPart("upload",
new FileBody(file, MULTIPART_FORM_DATA, filename));
exchange.getIn().setBody(multipartEntityBuilder.build());
}
})
.to("http4://localhost:8080/restwb/upload");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DeckerEgo |
| Solution 2 |
