Home > Mobile >  How to get a image/png with Ktor client get request?
How to get a image/png with Ktor client get request?

Time:04-24

I am trying to do a get request from a client get call to my server. My server response with a image/png content type. How can I recieve the image from my kotlin code?

CodePudding user response:

You're going to want to serve static content from your Ktor server: https://ktor.io/docs/serving-static-content.html

You create a static folder, then put your images in there:

static("/") {
    staticRootFolder = File("files")
}

After that's set up, you can reference files in that folder. If you want files in subfolders as well, you can add an extra files(".") line:

static("/") {
    staticRootFolder = File("files")
    files(".")
}

CodePudding user response:

You can download not only an image but also any other file.

Create ktor-client as you usually do.

val client = HttpClient(OkHttp) {
    install(ContentNegotiation) {
        json(Json { isLenient = true; ignoreUnknownKeys = true })
    }
}

For downloading a file using this client, read response using bodyAsChannel() which reads the response as ByteReadChannel. Use copyAsChannel() to write the data on the disk, passing destination's ByteWriteChannel.

GlobalScope.launch(Dispatchers.IO) {
    val url = Url("FILE_DOWNLOAD_LINK")
    val file = File(url.pathSegments.last())
    client.get(url).bodyAsChannel().copyAndClose(file.writeChannel())
    println("Finished downloading..")
}
  • Related