Spring

RestTemplate을 통해 파일 업로드하기

기록만이살길 2020. 6. 15. 22:15
반응형

1. 개요

이 빠른 튜토리얼은 Spring의 RestTemplate을 사용하여 멀티 파트 파일을 업로드하는 방법에 중점을 둡니다.

RestTemplate을 사용하여 업로드하는 단일 파일과 여러 파일이 모두 표시 됩니다.

2. HTTP Multipart Request 란?

간단히 말해서, 기본 HTTP POST 요청 본문은 양식 데이터를 key / 값 쌍으로 보유합니다.

반면, HTTP 클라이언트는 HTTP 멀티 파트 요청을 구성하여 텍스트 또는 이진 파일을 서버로 보낼 수 있습니다. 주로 파일 업로드에 사용됩니다.

또 다른 일반적인 사용 사례는 첨부 파일과 함께 이메일을 보내는 것입니다. 멀티 파트 파일 요청은 큰 파일을 작은 청크로 나누고 경계 마커를 사용하여 블록의 시작과 끝을 나타냅니다.

멀티 파트 요청에 대한 자세한 내용은 여기를 참조하십시오 .

3. Maven 의존성

이 단일 종속성은 클라이언트 응용 프로그램에 충분합니다.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

4. 파일 업로드 서버

파일 서버 API는 단일 및 다중 파일을 각각 업로드하기위한 두 개의 REST 엔드 포인트를 노출합니다.

  • POST / fileserver / singlefileupload /
  • POST / 파일 서버 / 여러 파일 업로드 /

5. 단일 파일 업로드

먼저 RestTemplate을 사용하여 단일 파일 업로드를 봅시다 .

헤더와 본문으로 HttpEntity 를 만들어야 합니다. 컨텐츠 유형 헤더 값을 MediaType.MULTIPART_FORM_DATA로 설정하십시오 . 이 헤더가 설정되면 RestTemplate 은 일부 메타 데이터와 함께 파일 데이터를 자동으로 마샬링합니다.

메타 데이터에는 파일 이름, 파일 크기 및 파일 내용 유형 (예 : text / plain )이 포함됩니다.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

다음으로 요청 본문을 LinkedMultiValueMap 클래스 의 인스턴스로 빌드하십시오 . LinkedMultiValueMapLinkedList의 각 키에 대한 여러 값을 저장하는 LinkedHashMap을 랩핑 합니다.

이 예제에서 getTestFile () 메소드는 더미 파일을 즉석에서 생성하고 FileSystemResource를 리턴합니다 .

MultiValueMap<String, Object> body  = new LinkedMultiValueMap<>();body.add("file", getTestFile());

마지막으로 헤더와 본문 객체를 감싸고 RestTemplate을 사용하여 게시 하는 HttpEntity 인스턴스를 생성하십시오 .

단일 파일 업로드는 / fileserver / singlefileupload / 엔드 포인트를 가리 킵니다 .

결국 restTemplate.postForEntity () 호출 은 주어진 URL에 연결하고 파일을 서버로 보내는 작업을 완료합니다.

HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);

6. 여러 파일 업로드

다중 파일 업로드에서 단일 파일 업로드의 유일한 변경 사항은 요청 본문을 구성하는 것입니다.

여러 파일을 만들고 MultiValueMap 에서 동일한 키사용하여 파일을 추가해 봅시다 .

분명히 요청 URL은 여러 파일 업로드를위한 엔드 포인트를 참조해야합니다.

MultiValueMap<String, Object> body  = new LinkedMultiValueMap<>();body.add("files", getTestFile());body.add("files", getTestFile());body.add("files", getTestFile());     HttpEntity<MultiValueMap<String, Object>> requestEntity  = new HttpEntity<>(body, headers); String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate  .postForEntity(serverUrl, requestEntity, String.class);

다중 파일 업로드를 사용하여 단일 파일 업로드모델링 할 수 있습니다.

7. 결론

결론적으로 Spring RestTemplate을 사용한 MultipartFile 전송 사례를 보았습니다 .

항상 그렇듯이 예제 클라이언트 및 서버 소스 코드는 GitHub에서 사용할 수 있습니다 .

참고

https://www.baeldung.com/spring-rest-template-multipart-upload

반응형