https://kotlinlang.org logo
#ktor
Title
# ktor
s

Suresh Maidaragi

11/16/2023, 11:47 AM
Hi there, i'm not able to add exact import for
File
, can someone help to check what we have missed, for this below import still we are seeing error
Copy code
import io.ktor.http.ContentDisposition.Companion.File
j

jamshedalamqaderi

11/16/2023, 11:48 AM
You need to import from
java.nio
package
a

Aleksei Tirman [JB]

11/16/2023, 11:49 AM
What platform do you write your code for (JVM, nix, darwin, etc)?
s

Suresh Maidaragi

11/16/2023, 11:50 AM
Kotlin multiplatform for iOS and Android
probably JVM
j

jamshedalamqaderi

11/16/2023, 11:51 AM
are you trying to access it from shared module?
s

Suresh Maidaragi

11/16/2023, 11:52 AM
Yes
j

jamshedalamqaderi

11/16/2023, 11:52 AM
then you need to create an actual/expect function to read file as bytearray in androidMain and iosMain
s

Suresh Maidaragi

11/16/2023, 4:59 PM
Thanks a lot @jamshedalamqaderi for quick response, it saved my time
I created the actual and expected as below but when I run iOS build for this code it showing build error,
Copy code
//androidmain

actual class FileUtils actual constructor() {
     actual fun readFileAsByteArray(filePath: String): ByteArray {
        val file = File(filePath)
        return file.readBytes()
    }
}
Copy code
///commonMain
expect class FileUtils() {
     fun readFileAsByteArray(filePath: String): ByteArray
}
Copy code
//iosMain

actual  class FileUtils actual constructor(){
    actual fun readFileAsByteArray(filePath: String): ByteArray {
        val fileURL = NSURL.fileURLWithPath(filePath)
        val data = NSData.dataWithContentsOfURL(fileURL)
        return data?.toByteArray() ?: ByteArray(0)
    }

    @OptIn(ExperimentalForeignApi::class)
    private fun NSData.toByteArray(): ByteArray {
        val length = this.length.toInt()
        val bytes = ByteArray(length)
        this.getBytes(bytes)
        return bytes
    }
}
here is the build error
j

jamshedalamqaderi

11/17/2023, 8:35 AM
try this
Copy code
val b = ByteArray(d.length.toInt()).apply {
        usePinned {
                memcpy(it.addressOf(0), d.bytes, d.length)
        }
  }