使用 Spring Boot RestTemplate 傳送檔案到 api 伺服器 (MultipartFile, form)
- 用戶端可以使用Html Form傳輸文件,但SpringBoot伺服器也可以直接將文件傳輸到另一台伺服器。
- 讓我們學習如何使用 RestTemplate 傳輸檔案。
檔案傳輸相關原始碼
- 我們只簡單看一下最重要的邏輯。
- 建立標題。在標頭中設定
Content-Type: multipart/form-data
。 - 當傳送文件時,並不是立即傳送文件,而是需要將其變更為**ByteArrayResource。 ** 將其轉換為ByteArrayResource,並將其新增至正文中。
- 您可以建立一個Request物件用於檔案傳輸或使用map傳送。
- 建立標題。在標頭中設定
- 就我個人而言,我不確定以什麼格式傳送文件,但我學習如何使用 ByteArrayResource 傳送文件。
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
}