14 Haziran 2023 Çarşamba

SpringMVC MultipartBodyBuilder Sınıfı

Giriş
Açıklaması şöyle
MultipartBodyBuilder is a class in the Spring Framework that provides a fluent API for constructing a multipart/form-data request body. This type of request is commonly used to upload files to a server.

A common use case for MultipartBodyBuilder is in a microservices architecture where you want to transfer a multipart file from one service to another.
Örnek
Elimizde şöyle bir kod olsun
@RestController
@CrossOrigin
@RequiredArgsConstructor
@RequestMapping(value = "/send-multipartfile")
@Slf4j
public class APIGatewayController {
    
  @PostMapping(value = "/post-multipart-data", consumes = MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON_VALUE)
  @Operation(
     operationId = "sendMultipartFileToSampleService",
     summary = "To upload multipart file and send it to sample micro-service, Call this API",
     description = "sendMultipartFileToSampleService method is HTTP POST mapping so upload file to send to micro-service."
   )
  public ResponseEntity<Response> sendMultipartFileToSampleService(@RequestParam("file") @Valid MultipartFile file) {
    return ResponseEntity.ok(
      sendMultipartFile( file, "<ip-address>:<port>/receive-multipartfile/get-multipart-data")
    );
  }
}
Şöyle yaparız. Burada MappingJackson2HttpMessageConverter kullanılarak MULTIPART_FORM_DATA verisi JSON olarak gönderiliyor
public Response sendMultipartFile(MultipartFile file, String apiValue) {
  // response to be return to request.
  Response returnResponse = new Response();
  RestTemplate restTemplate = new RestTemplate();

  try {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(MediaType.MULTIPART_FORM_DATA);
    restTemplate.getMessageConverters().add(converter);

    // Create a new MultipartBodyBuilder
    MultipartBodyBuilder builder = new MultipartBodyBuilder();

    builder.part("file", file.getResource());
    // Set the content type to "multipart/form-data"
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    // Create a new HttpEntity using the MultipartBodyBuilder
    HttpEntity < MultiValueMap < String, HttpEntity << ? >>> requestEntity = new HttpEntity < > (builder.build(), headers);

    // Send the request and get the response
    Response apiResponse = restTemplate.exchange(
      apiValue, HttpMethod.POST, requestEntity, Response.class).getBody();

    log.info("Getting response from API: {}...", apiValue);
    if (apiResponse != null) {
      // getting data of storageConfigResponse
      log.info("Response from api: {} is fetched successfully!", apiValue);
      returnResponse = apiResponse;
      return returnResponse;
    } else {
      log.info("Response of API: [{}] is coming null. Please Check!", apiValue);
    }
  } catch (Exception exception) {
    log.error("Failed to call API: [{}], Reason is: {} ", apiValue, exception.getMessage());
    returnResponse.setResponseTime(LocalDateTime.now());
    returnResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
    returnResponse.setMessage("Internal Server Error");
    returnResponse.setExecutionMessage(apiValue);
  }
  return returnResponse;
}

Hiç yorum yok:

Yorum Gönder