본문으로 건너뛰기

Spring Boot RestTemplate 을 이용하여 api 서버에 File 전송하기(MultipartFile, form)

  • Html Form 을 이용하여 client 에서 File 을 전송할 수도 있지만, SpringBoot 서버가 직접 파일을 다른 서버로 전송할 수도 있다.
  • RestTemplate 을 이용하여 File 을 전송하는 방법을 알아보자.

File 전송 관련 소스코드

  • 가장 중요한 로직만 간단하게 살펴보자.
    • Header 를 생성한다. Header 에는 Content-Type: multipart/form-data 를 설정한다.
    • File 을 전송할 때에는 File 을 바로 보내는 것이 아니라, ByteArrayResource 로 변경하는 작업이 필요하다. ByteArrayResource 로 변환하여 body 에 추가한다.
    • File 전송을 위한 Request 객체를 생성하거나, map 을 이용하여 전송할 수 있다.
  • 개인적으로는 File 을 어떤 형식으로 보내야할지 잘 몰랐었는데, ByteArrayResource 를 이용하여 File 을 전송하는 방법을 알게 되었다.
fun uploadToOtherServer() {
// 1. Create headers
val headers = HttpHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA

// 2. File -> ByteArrayResource
val contentsAsResource = object : ByteArrayResource(uploadRequest.file.readBytes()) {
override fun getFilename(): String {
return uploadRequest.file.name
}
}

// 3. Create a MultiValueMap to set the form parameters
// Add other information if you need
val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
body.add("file", contentsAsResource)
body.add("createdAt", uploadRequest.createdAt)

// 4. Send the request
val requestEntity: HttpEntity<MultiValueMap<String, Any>> = HttpEntity(body, headers)
val responseEntity = restTemplate.postForEntity<Any>(
"http://endpoint-url.com/upload", // endpoint url
requestEntity
)

// Add your logic here
}