본문 바로가기

html | javascript

html javascript - input txt file

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>input txt file</title>
</head>
<body onload="init()">
  <input id="id-input" type="file" accept=".txt" multiple />
  <br>
  <br>
  <label id="id-label"></label>

  <script>
    let input
    let label

    function init() {
      label = document.getElementById('id-label')
      input = document.getElementById('id-input')
      input.addEventListener('change', onChangeInput)
    }

    function onChangeInput() {
      const files = input.files
      for (const file of files) {
        const reader = new FileReader()
        reader.addEventListener('load', () => {
          const txt = reader.result
          label.innerText = txt
        })
        reader.readAsText(file)
      }
    }
  </script>
</body>
</html>