[kotlin] Ktor 클라이언트 라이브러리를 이용한 파일 업로드 및 다운로드
Ktor는 Kotlin 기반의 웹 어플리케이션을 개발하기 위한 오픈 소스 라이브러리이며, 클라이언트 라이브러리를 이용하면 간단하게 파일 업로드와 다운로드 기능을 구현할 수 있습니다.
이번 예제에서는 Ktor 클라이언트 라이브러리를 사용하여 파일을 업로드하고 다운로드하는 방법에 대해 알아보겠습니다.
파일 업로드
아래는 Ktor 클라이언트 라이브러리를 사용하여 파일을 업로드하는 예제입니다.
import io.ktor.client.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import kotlinx.coroutines.runBlocking
import java.io.File
fun main() {
val client = HttpClient()
val file = File("example.txt")
runBlocking {
val response: HttpResponse = client.post("http://server/upload") {
body = MultiPartFormDataContent(formData {
appendInput("file", Headers.build {
append(HttpHeaders.ContentType, ContentType.Text.Plain.toString())
append(HttpHeaders.ContentDisposition, "filename=${file.name}")
}, size = file.length()) {
file.forEachBlock { buffer, bytesRead ->
writeFully(buffer, 0, bytesRead)
}
}
})
}
if (response.status.isSuccess()) {
println("File uploaded successfully")
} else {
println("Failed to upload file")
}
}
}
위 예제에서는 HttpClient
를 사용하여 파일을 업로드하는 과정을 보여줍니다. MultiPartFormDataContent
를 사용하여 파일을 포함한 요청을 생성하고, client.post
를 통해 서버에 업로드를 요청합니다.
파일 다운로드
이번에는 Ktor 클라이언트 라이브러리를 사용하여 파일을 다운로드하는 예제를 살펴보겠습니다.
import io.ktor.client.*
import io.ktor.client.request.*
import kotlinx.coroutines.runBlocking
import java.io.File
fun main() {
val client = HttpClient()
runBlocking {
val fileBytes: ByteArray = client.get("http://server/download")
val outputFile = File("downloaded_file.txt")
outputFile.writeBytes(fileBytes)
println("File downloaded successfully")
}
}
위 예제에서는 HttpClient
를 사용하여 파일을 다운로드합니다. client.get
을 통해 서버에서 파일을 다운로드하고, File
을 사용하여 바이트를 파일로 저장합니다.
Ktor 클라이언트 라이브러리를 사용하면 웹 어플리케이션에서 파일 업로드와 다운로드를 간편하게 처리할 수 있습니다.
위 예제에서는 간단한 파일 업로드와 다운로드만을 다루었지만, 실제 프로젝트에서는 보안과 성능 등을 고려하여 더 많은 기능을 추가할 수 있습니다.
참고 문헌: