简体   繁体   中英

Spring WebClient multipart/form-data request, Could not able to send file

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM