3

So I'm trying to send a file over HTTP using Java's webclient and in addition to the file I want to send a mono with some info. Client side:

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;
    }

And server side:

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

However this fails with:

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

Not sure what I am missing here, can anyone assist please?

1 Answers1

0

Set the consumes property of your @PostMapping to MediaType.MULTIPART_FORM_DATA_VALUE. Right now it either inherits the accepted media types from a class annotation, or if absent just supports the defaults. Those defaults don't include multipart/formdata.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20