r/JavaScriptTips • • Feb 02 '23

Read the contents of a user-selected file using the FileReader object 📖

Post image
13 Upvotes

1 comment sorted by

1

u/Low_Mammoth_9371 Feb 02 '23

Code to copy below, full YT tutorial (also on image editing) here: https://youtu.be/u2VTtAXq1iA

<input type="file" accept="text/*">

<script>

  const inputEl = document.querySelector('[type="file"]');

  inputEl.addEventListener('change', () => {

      const file = inputEl.files[0];

      const fr = new FileReader(); 

      fr.readAsText(file);

      fr.addEventListener('load', () => {
        
          console.log(fr.result);
          // Hello from text file 👋
        
      })
  });

  </script>