I want to get file from source directory and upload it to the API rest service with multipart by using http apache camel.
How can I do multipart file uploads using the Apache Camel HTTP component ?
Can I use camel-platform-http component ?
I've found the solution to transfer files from specific folder to HTTP API service by using 4.10.5 camel version
dependencies to import in the project:
implementation group: 'org.apache.camel', name: 'camel-http', version: '4.10.5'
implementation("org.apache.httpcomponents.core5:httpcore5:5.3.4")
Route example:
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import com.bh.fileservice.processors.FileProcessor;
@Component(value = "fileToHttpMultipart")
public class FileToHttpMultipart extends RouteBuilder {
@Override
public void configure() throws Exception {
from("file:C:\\tmp\\input?delay=5000&delete=true").threads(3, 4)
.process(new FileProcessor())
.log("Body: ${body}")
.to("http://localhost:8081/v1/handler/camel/uploadFile?httpMethod=POST").routeId("uploadFile").end();
}
}
Processor example:
import java.io.File;
import java.io.FileInputStream;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.commons.io.FileUtils;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
public class FileProcessor implements Processor {
private static final Logger LOGGER = LogManager.getLogger(FileProcessor.class);
@Override
public void process(Exchange exchange) throws Exception {
File file = exchange.getIn().getBody(File.class);
exchange.getIn().setBody(MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, file.getName()).build());
}
}
**
API Service** and Multipart config example:
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.ofMegabytes(900L));
factory.setMaxRequestSize(DataSize.ofMegabytes(900L));
return factory.createMultipartConfig();
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
@ResponseBody
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
try {
String name = file.getOriginalFilename();
long size = file.getSize();
LOGGER.info("fileName: " +name +" file size: " + size );
}
catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}