Java webclient中多部分请求的正确格式。

3

我正在尝试使用Java的WebClient通过HTTP发送文件,除了文件外,我还想发送一个带有一些信息的mono。客户端代码如下:

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]

我不确定我错过了什么,有人能帮忙吗?

1个回答

0

将您的@PostMappingconsumes属性设置为MediaType.MULTIPART_FORM_DATA_VALUE。目前它要么从类注释继承接受的媒体类型,要么如果缺失则支持默认值。这些默认值不包括multipart/formdata


谢谢您的建议,不幸的是它没有解决问题,还有其他建议吗? - Barak Sason Rofman
你能展示一下类的注解和新方法声明吗? - Rob Spoor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接