Java web客户端中多部分请求的正确形式



所以我试图使用Java的web客户端通过HTTP发送文件,除了文件之外,我还想发送一个带有一些信息的单声道。客户端:

public int create(String filePath, String dirPath) {
File file = new File(filePath);
byte[] fileContent = null;
try {
fileContent = Files.readAllBytes(file.toPath());
} catch (IOException e) {
return -1;
}
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("uploadfile", new ByteArrayResource(fileContent)).header("Content-Disposition",
"form-data; name=file; filename=%s;", file.getName());
builder.asyncPart("fileInfo", Mono.just(new FileInfo(file.getName(), dirPath)), FileInfo.class)
.header("Content-Disposition", "form-data; name=fileInfo;");
String response = null;
try {
response = webClient.post().uri("create").contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(builder.build())).retrieve().bodyToMono(String.class).block();
} catch (WebClientResponseException e) {
System.out.println("Error " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
return -1;
}
System.out.println(response);
return 0;
}

服务器端:

@PostMapping("/create")
public ResponseEntity<String> create(@RequestBody MultipartFile file, @RequestBody FileInfo fileInfo) {
<Proccesing>
return ResponseEntity.status(HttpStatus.CREATED).body("Successfully created " + filePath);
}

但是,如果使用:

Content type 'multipart/form-data;boundary=uJ7S5afzny4V3wTNWemPvW8rHVTEa6qxC5YS0D;charset=UTF-8' not supported]

不知道我在这里错过了什么,有人能帮助吗?

设置@PostMappingconsumes属性为MediaType.MULTIPART_FORM_DATA_VALUE。现在,它要么从类注释中继承可接受的媒体类型,要么在没有媒体类型的情况下只支持默认类型。这些默认值不包括multipart/formdata

最新更新