メインコンテンツにスキップ

Spring Boot RestTemplateを使用してapiサーバーにファイルを転送する(MultipartFile、form)

  • Html Formを使用してclientからFileを転送することもできますが、SpringBootサーバーが直接ファイルを別のサーバーに転送することもできます。
  • RestTemplateを使ってファイルを転送する方法を学びましょう。

File転送関連ソースコード

*最も重要なロジックだけを簡単に見てみましょう。

  • Header を生成する。 Header には Content-Type: multipart/form-data を設定する。
  • Fileを転送するときは、Fileを直接送信するのではなく、**ByteArrayResourceに変更する作業が必要です。**ByteArrayResourceに変換してbodyに追加する。 *ファイル転送用の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
}