Webclient MultiPart File Upload

By | 2020년 8월 12일

MultipartBodyBuilder와 WebClient를 이용한 MultiPart FormData 전송 예제

    URI uri = URI.create("https://aaa.aaa/upload");

    File file = new File("/tmp/1234.jpg");
    byte[] fileContent = Files.readAllBytes(file.toPath());

    MultipartBodyBuilder builder = new MultipartBodyBuilder();
    builder.part("name", "david");
    builder.part("version", "1.1.0");
    builder.part("uploadfile", new ByteArrayResource(fileContent))
        .header("Content-Disposition",
            "form-data; name= uploadfile; filename=1234.jpg");

    String response =  WebClient.create()
        .method(HttpMethod.POST)
        .uri(uri)
        .contentType(MediaType.APPLICATION_JSON)
        .body(BodyInserters.fromMultipartData(builder.build()))
        .exchange()
        .block()
        .bodyToMono(String.class)
        .doOnError(e -> log.error("Mapping Error : ", e))
        .block();