【问题标题】:Spring WebClient multipart/form-data request, Could not able to send fileSpring WebClient 多部分/表单数据请求,无法发送文件
【发布时间】:2020-10-12 10:29:13
【问题描述】:

我试图通过 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(); 

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

我也累了

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

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

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

【问题讨论】:

    标签: java spring-boot resttemplate spring-webclient


    【解决方案1】:

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

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

    MutipartBody builder

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2018-03-05
      • 1970-01-01
      • 2016-11-11
      • 2020-04-10
      相关资源
      最近更新 更多