Tech Tip – Calling a Rest service for file upload

During a recent project I had to call a REST Api to upload files. Talend offers several REST solutions, but none of them include the option to upload a file out of the box.

This solution is based on standard Java libraries and uses okio en okhttp libraries. First step is to do a tLibraryLoad on these 2 libraries. The final step is just a few lines of java code to execute the API request

RestFileUpload

Add the following code to the tJava component


OkHttpClient client = new OkHttpClient();
File sourceFile = new File("C:\\xsed.png");
MediaType mediaType = MediaType.parse("multipart/form-data");
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "C:\\xsed.png",RequestBody.create(MediaType.parse("image/png"), sourceFile) )
.addFormDataPart("objectName", "project")
.addFormDataPart("objectProperty", "documents")
.addFormDataPart("objectId", context.newProjectId)
.build();
Request request = new Request.Builder()
.url("https://api.yoursite.com/api/fileUpload")
.post(body)
.addHeader("content-type", "multipart/form-data")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
String json = response.body().string();
System.out.println(json.toString());

Depending on your REST Api the actual code may vary a bit. You can check the Okhttp documentation for all options.

References:
Okhttp sources
http://square.github.io/okhttp/

Okio sources
https://github.com/square/okio

Alternative solution on how to on modying the tRestClient component
https://www.talendforge.org/forum/viewtopic.php?id=40341

Pin it

Stefan is an experienced data management consultant with many years of experience in business intelligence and data integration. Recently his focus shifted towards Big Data and the Internet of Things.

Website: http://www.xsed.nl

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *

FacebookTwitterGoogle+RSS