MuptipartFile RestTemplate 으로 전송하기

이담호·2025년 2월 13일

상황

프로젝트를 진행하던 중 MuptipartFile을 RestTemplate으로 front -> back 전송해야하는 상황이었다.

public void fileUpload(MultipartFile file) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultipartFile> requestEntity = new HttpEntity<>(file, headers);

        restTemplate.exchange(
                backAdaptorProperties.getAddress() + URL,
                HttpMethod.POST,
                requestEntity,
                new ParameterizedTypeReference<> () {}
        );
    }

2025-02-13 16:08:15.930 [http-nio-8080-exec-1] ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.web.client.RestClientException: No HttpMessageConverter for org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile and content type "multipart/form-data"] with root cause
org.springframework.web.client.RestClientException: No HttpMessageConverter for org.springframework.web.multipart.support.StandardMultipartHttpServletRequestStandardMultipartFileandcontenttype"multipart/formdata"atorg.springframework.web.client.RestTemplateStandardMultipartFile and content type "multipart/form-data" at org.springframework.web.client.RestTemplateHttpEntityRequestCallback.doWithRequest(RestTemplate.java:1146)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:898)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:801)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:712)
at com.example.front.file.adaptor.FileAdaptor.fileUpload(FileAdaptor.java:30)
at com.example.front.file.service.FileService.fileUpload(FileService.java:14)


원인

...

해결

public void fileUpload(MultipartFile file) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();

        try {
            body.add("file", new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        HttpEntity<MultiValueMap<String, Object>> requestEntity =
                new HttpEntity<>(body, headers);
        URI uri = UriComponentsBuilder.fromUriString(backAdaptorProperties.getAddress() + URL).build().toUri();

        restTemplate.exchange(
                uri,
                HttpMethod.POST,
                requestEntity,
                new ParameterizedTypeReference<>() {}
        );
    }

MultipartFile을 MultiValueMap으로 감싸서 보내 성공했다.

0개의 댓글