Sending a file to the api server using Spring Boot RestTemplate (MultipartFile, form)
- Files can be transmitted from the client using Html Form, but the SpringBoot server can also directly transmit files to another server.
- Let’s learn how to transfer a file using RestTemplate.
Source code related to file transfer
- Let’s briefly look at only the most important logic.
- Create Header. Set
Content-Type: multipart/form-data
in Header. - When sending a file, you do not send the file right away, but you need to change it to ByteArrayResource. Convert it to ByteArrayResource and add it to the body.
- You can create a Request object for file transfer or send it using map.
- Create Header. Set
- Personally, I was not sure what format to send the file in, but I learned how to send the file using 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
}