简体   繁体   中英

How to upload file with Spring 5 webClient

I try to upload files with webClient Spring5 (multipart/form-data), but I got 400 Badrequest there is my code (when i try with restTemplate all work fine), don't understand why not work with webclient, any help is precious, thanks in advance...

MultipartBodyBuilder builder = new MultipartBodyBuilder();

builder.part("subject", parametres.getSubject());

builder.part("lifetime", parametres.getLifeTime());

builder.part("comment", parametres.getComment());

builder.part("encrypted", parametres.getEncrypted());

builder.part("file", new FileSystemResource(file)).filename(file.getName()) //file is a java.io.File`
ClientResponse response = getClient().post()
     .uri("/messages")
     .body(BodyInserters.fromMultipartData(builder.build()))
     .header(PlinePlexHeaderEnum.HTTP_HEADER_PROCURATION_USER_ID.value(), idUser))
     .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
     .exchange().block();

Try this:

  final WebClient webClient = webClientBuilder.build();
        webClient.post()
            .uri("http://hostname:port/messages")
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .header(PlinePlexHeaderEnum.HTTP_HEADER_PROCURATION_USER_ID.value(), idUser))
            .body(BodyInserters.fromMultipartData(buildMultipartBody(file, parametres)))
            .retrieve()
            .bodyToMono(String.class)
            .block();
        }

        private MultiValueMap < String, HttpEntity << ? >> buildMultipartBody(private File file, private Parametres parametres) {
            MultipartBodyBuilder builder = new MultipartBodyBuilder();
            builder.part("file", new FileSystemResource(file));
            builder.part("subject", parametres.getSubject());       `
            builder.part("lifetime", parametres.getLifeTime());`
            builder.part("comment", parametres.getComment());   `
            builder.part("encrypted", parametres.getEncrypted());`
            return builder.build();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM