hey <@U02AB5P2XU6>, I stumbled on this thread whil...
# kobweb
d
hey @David Herman, I stumbled on this thread while searching for a way to load multiple images from disk (https://kotlinlang.slack.com/archives/C04RTD72RQ8/p1700592869272569) and saw you didn't have a function for it in your FileUtils class. I needed it for a personal project and tried to create a function by using your example. Did I overlook your implementation for it ? Do you think my implementation would be fine? Could their be any improvements? I'm not really experienced in working with webforms and files. If there are other people who have need of a similar implementation you can find it below
Copy code
private fun <I, O> Document.loadMultipleFromDisk(
    accept: String = "",
    triggerLoad: FileReader.(Blob) -> Unit,
    deserialize: (I) -> O,
    onLoading: (List<Pair<LoadContext, O>>) -> Unit,
) {
    val tempInput = (createElement("input") as HTMLInputElement).apply {
        type = "file"
        style.display = "none"
        this.accept = accept
        multiple = true
    }

    tempInput.onchange = { changeEvt ->
        val selectedFiles = changeEvt.target.asDynamic().files
        val length = selectedFiles.length as Int
        val loadedFiles = arrayListOf<Pair<LoadContext, O>>()

        for (i in 0 until length) {
            val reader = FileReader()
            val file = selectedFiles[i] as File
            reader.onload = { loadEvt ->
                val result = loadEvt.target.asDynamic().result as I
                loadedFiles.add(LoadContext(file.name, file.type.takeIf { it.isNotBlank() }) to deserialize(result))
                onLoading(loadedFiles)
            }
            reader.triggerLoad(file)
        }
    }
    body!!.append(tempInput)
    tempInput.click()
    tempInput.remove()
}

fun Document.loadMultipleDataUrlFromDisk(
    accept: String = "",
    onLoaded: (List<Pair<LoadContext, String>>) -> Unit,
) {
    loadMultipleFromDisk<String, String>(
        accept,
        FileReader::readAsDataURL,
        { result -> result },
        onLoaded
    )
}
d
It's likely I overlooked it. I will take a look at your implementation later today when I get to my desk!
This looks useful. I'll reach out to you shortly about integrating it into Kobweb with your permission.
d
Ok nice!! Happy to contribute 🙂