java - 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));
我找不到哪里出错了。任何帮助。
解决方案
我是用wong方式做的,文件应该作为资源给出,代码如下
public static Resource getTestFile() {
return new FileSystemResource(new File("C:\\Users\\Desktop\\abc.docx"));
}
MutipartBody builder
bodyBuilder.part("attachmentName", getTestFile());
推荐阅读
- c# - 调整用作水印的位图大小,结果显示深色边框
- subscription - 在 DolphinDB 中重新订阅
- spring-boot - jhipster 无法将 spring 运行配置文件更改为 prod - 始终以 dev、swagger 开头 - Maven as Service
- python - Abaqus 脚本 KeyError
- javascript - Django-bootstrap-datepicker-plus 未正确呈现日期选择器
- r - 迭代计算 ./ dplyr 函数中大型数据集均值的变异
- python - 在 Python 中使用进程时的空列表
- javascript - Nuxt 定制路由器
- swift - 如何将单元格中的文本字段作为出口快速连接到表格视图单元格类
- python - 使用 Pytorch Mask RCNN 时的零除错误