Reputation: 657
Im trying to hit an endpoint which accepts multipart/file request via WebClient, code as follows
WebClient webClient = WebClient.builder().baseUrl(urlServer).build();
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("name", "myname"));
MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
form.forEach(k -> bodyBuilder.part(k.getName(), k.getValue(), MediaType.TEXT_PLAIN));
// file
File file = new File(getClass().getClassLoader().getResource("abc.yaml").getFile());
bodyBuilder.part("attachmentName", file);
String response = webClient.post()
.contentType(MediaType.MULTIPART_FORM_DATA)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromMultipartData(bodyBuilder.build())).exchange()
.block()
.bodyToMono(String.class)
.block();
Hit to the desired endpoint is success and 'name' filed value is retrieved as given. But the file data is empty.
I also tired
byte[] templateContent = org.springframework.util.FileCopyUtils.copyToByteArray(
new File(getClass().getClassLoader().getResource("abc.yaml").getFile()));
bodyBuilder.part("attachmentName", new ByteArrayResource(templateContent));
I could not find where I am going wrong. Any help.
Upvotes: 1
Views: 3305
Reputation: 657
I did it in wong way, File should be given as a resource, Code as follows
public static Resource getTestFile() {
return new FileSystemResource(new File("C:\\Users\\Desktop\\abc.docx"));
}
MutipartBody builder
bodyBuilder.part("attachmentName", getTestFile());
Upvotes: 3