본문 바로가기
Spring Spring boot

[Spring] RestTemplate으로 MultipartFile 단일 업로드

by cooky2 2021. 10. 26.

HTTP 멀티 파트 요청이란? 

 

HTTP 클라이언트는 HTTP 멀티 파트 요청을 구성하여 텍스트 또는 바이너리 파일을 서버로 보낼 수 있다.

주로 파일 업로드에 사용된다. 다른 예시로 첨부 파일과 함께 이메일을 보낼 때 사용하기도 한다. 

 

 

private void callFileUpdateApi(int contentId, MultipartFile file) 
	{
		//RestTemplate을 이용한 단일 파일 업로드 
		HttpHeaders headers = new HttpHeaders(); //헤더와 본문이 있는 HttpEntity를 만든다. 
		headers.setContentType(MediaType.MULTIPART_FORM_DATA); //헤더값을 설정해주면 RestTemplate은 일부 메타 데이터와 함께 파일 데이터를 자동으로 마샬링 한다.
		
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(); //LinkedMultiValueMap은 LinkedList의 각 키에 대해 여러 값을 저장하는 LinkedHashMap을 래핑 
		body.add("contentId", contentId);
		body.add("file", file.getResource()); //리소스 보내기
        
		HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String,Object>>(body, headers); //헤더와 본문 개체를 감싸는 HttpEntity 인스턴스를 생성하고 RestTemplate을 사용하여 게시한다.      
		ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/movieon/contents/editThumbnail", entity, String.class); //restTemplate.postForEntity() 호출은 주어진 URL에 연결하고 파일을 서버로 보내는 작업을 완료 
	}

** 마샬링이란? 

하나 이상의 프로그램 또는 연속되어 있지 않은 저장 공간으로부터 데이터를 모은 다음, 데이터들을 메시지 버퍼에 집어넣고,

특정 수신기나 프로그래밍 인터페이스에 맞도록 그 데이터를 조직화하거나, 미리 정해진 다른 형식으로 변환하는 과정 

'Spring Spring boot' 카테고리의 다른 글

[JSP] <c:forEach> 태그 사용하기  (0) 2021.10.12
[Spring] Interceptor 란 ?  (0) 2021.10.07
[Spring boot] Controller/service/dao/dto  (0) 2021.10.07

댓글