RestTemplate의 멀티파트 파일 업로드 및 다운로드 구현하기
RestTemplate은 Spring 프레임워크에서 제공하는 HTTP 통신을 간단하게 처리할 수 있는 유틸리티 클래스입니다. 이번에는 RestTemplate을 사용하여 멀티파트 파일 업로드 및 다운로드를 구현하는 방법에 대해 알아보겠습니다. 멀티파트 파일은 파일 데이터뿐만 아니라 파일 이름, 파일 타입 등의 정보를 함께 전송하는 방식입니다.
RestTemplate를 사용한 멀티파트 파일 업로드 구현
RestTemplate을 사용하여 멀티파트 파일을 업로드하는 방법은 다음과 같습니다.
RestTemplate restTemplate = new RestTemplate();
MultiValueMap body = new LinkedMultiValueMap();
body.add("file", new FileSystemResource("/path/to/file"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap> requestEntity = new HttpEntity(body, headers);
String url = "//example.com/upload";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
위 코드에서는 MultiValueMap
을 사용하여 파일 데이터와 파일 정보를 함께 전송하고, HttpHeaders
를 사용하여 Content-Type
을 multipart/form-data
로 설정합니다. 그리고 HttpEntity
를 생성하여 MultiValueMap
과 HttpHeaders
를 함께 전송하고, RestTemplate.exchange()
메서드를 호출하여 서버로 데이터를 전송합니다.
RestTemplate를 사용한 멀티파트 파일 다운로드 구현
RestTemplate을 사용하여 멀티파트 파일을 다운로드하는 방법은 다음과 같습니다.
RestTemplate restTemplate = new RestTemplate();
String url = "//example.com/download";
ResponseEntity responseEntity = restTemplate.getForEntity(url, byte[].class);
byte[] fileData = responseEntity.getBody();
위 코드에서는 RestTemplate.getForEntity()
메서드를 호출하여 서버에서 파일 데이터를 받아옵니다. ResponseEntity
객체를 사용하여 파일 데이터와 함께 HTTP 응답 정보를 받아올 수 있습니다.
RestTemplate 멀티파트 파일 업로드 및 다운로드 구현 예제
RestTemplate을 사용하여 멀티파트 파일 업로드 및 다운로드를 구현하는 예제를 살펴보겠습니다. 이 예제는 Spring Boot를 사용하여 구현되었습니다.
@RestController
public class FileController {
private final RestTemplate restTemplate;
public FileController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
MultiValueMap body = new LinkedMultiValueMap();
body.add("file", new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
return file.getOriginalFilename();
}
});
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap> requestEntity = new HttpEntity(body, headers);
String url = "//localhost:8080/download";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
}
@GetMapping("/download")
public ResponseEntity downloadFile() throws IOException {
String filePath = "/path/to/file";
File file = new File(filePath);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
byte[] fileData = Files.readAllBytes(file.toPath());
return new ResponseEntity(fileData, headers, HttpStatus.OK);
}
}
위 코드에서는 /upload
엔드포인트에서 MultipartFile
을 받아와서 MultiValueMap
을 생성하여 RestTemplate.exchange()
메서드를 호출하여 파일을 업로드합니다. /download
엔드포인트에서는 파일을 읽어와서 ResponseEntity
객체를 생성하여 파일 다운로드를 구현합니다.
이번에는 RestTemplate을 사용하여 멀티파트 파일 업로드 및 다운로드를 구현하는 방법에 대해 알아보았습니다. RestTemplate은 Spring 프레임워크에서 제공하는 유틸리티 클래스로 HTTP 통신을 간단하게 처리할 수 있어 매우 유용합니다. 멀티파트 파일 업로드 및 다운로드는 파일 데이터뿐만 아니라 파일 이름, 파일 타입 등의 정보를 함께 전송해야 하기 때문에 조금 더 복잡한 방식으로 구현됩니다. 하지만 RestTemplate을 사용하면 간단하게 구현할 수 있습니다.