Kotlin / kotlinx.html

Kotlin DSL for HTML
Apache License 2.0
1.63k stars 133 forks source link

How to read uploaded file's content via FileReader API? #200

Closed shalva97 closed 2 years ago

shalva97 commented 2 years ago

I want to read contents of a file that will be selected in input tag. Here is the code that uses it via JS https://stackoverflow.com/a/44161989/4885394

How can I make same but in Kotlin? here is what i tried:

fun main() {

    val textArea by mutableStateOf("File contents will appear here")

    renderComposable(rootElementId = "root") {
        Div {
            Div {
                Label {
                    Text("Select a JSON file:")
                }
                Br()
                Input(InputType.File) {
                    addEventListener("change") {
                        // here I expect it.target.files to be an array
                        // but it is not resolved
                        if (it.target.files) {

                        }
                    }
                }
            }
            TextArea(textArea) {

            }
        }
    }
}

Here is the code, it is also in the link above but will write here also:

document.getElementById('input-file')
  .addEventListener('change', getFile)

function getFile(event) {
    const input = event.target
        if ('files' in input && input.files.length > 0) { // here is the part of code I can not convert to kotlin
            placeFileContent(
                      document.getElementById('content-target'),
                      input.files[0])
        }
}

function placeFileContent(target, file) {
    readFileContent(file).then(content => {
      target.value = content
    }).catch(error => console.log(error))
  }

  function readFileContent(file) {
      const reader = new FileReader()
    return new Promise((resolve, reject) => {
      reader.onload = event => resolve(event.target.result)
      reader.onerror = error => reject(error)
      reader.readAsText(file)
    })
}
shalva97 commented 2 years ago

I guess I asked this on wrong place...