首页 > 解决方案 > Spring WebClient 多部分/表单数据请求,无法发送文件

问题描述

我试图通过 WebClient 访问一个接受多部分/文件请求的端点,代码如下

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

命中所需的端点是成功的,并且“名称”字段值被检索为给定。但是文件数据是空的。

我也累

byte[] templateContent = org.springframework.util.FileCopyUtils.copyToByteArray(
new File(getClass().getClassLoader().getResource("abc.yaml").getFile()));

bodyBuilder.part("attachmentName",   new ByteArrayResource(templateContent));

我找不到哪里出错了。任何帮助。

标签: javaspring-bootresttemplatespring-webclient

解决方案


我是用wong方式做的,文件应该作为资源给出,代码如下

 public static Resource getTestFile() {
        return new FileSystemResource(new File("C:\\Users\\Desktop\\abc.docx"));
    }

MutipartBody builder

bodyBuilder.part("attachmentName",   getTestFile());

推荐阅读