compose-multiplatform
compose-multiplatform copied to clipboard
Web: Uploading a file
How would I upload a file from my browser via compose for web?
I have tried using the FileInput control but I am unable to grab the actual file?
I am using Ktor on the backend.
Are there any examples for uploading a file from compose for web?
Thanks
Not related to Compose, but simple JS file api:
@Composable
fun Upload(title: String, onDone: (ByteArray) -> Unit) {
Column {
var uploadButton: HTMLInputElement? = null
Input(type = InputType.File) {
hidden() // Hidden, because I dislike the HTML file button
accept(".xlsx") // optional
ref {
uploadButton = it
onDispose {
uploadButton = null
}
}
onChange {
val file: File = it.target.files!!.asList().single()
scope.launch {
file.buffer() // do something with its content, eg
}
}
}
Button(title) {
uploadButton?.value = "" // reset the previous file to upload a new file again
uploadButton?.click()
}
}
}
suspend fun Blob.buffer(): ArrayBuffer = suspendCoroutine {
FileReader().apply {
onload = { _ ->
it.resume(result as ArrayBuffer)
}
onerror = { _ ->
it.resumeWithException(Error("reading file: $this"))
}
}.readAsArrayBuffer(this)
}
fun ArrayBuffer.toByteArray(): ByteArray = Int8Array(this).unsafeCast<ByteArray>()