Reading uploaded text file contents in html

Solution 1:

I've came here from google and was surprised to see no working example.

You can read files with FileReader API with good cross-browser support.

const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries

See fully working example below.

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

function getFile(event) {
	const input = event.target
  if ('files' in input && input.files.length > 0) {
	  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)
  })
}
label {
  cursor: pointer;
}

textarea {
  width: 400px;
  height: 150px;
}
<div>
 <label for="input-file">Specify a file:</label><br>
 <input type="file" id="input-file">
</div>

<textarea id="content-target"></textarea>

Solution 2:

Here's one way:

HTML

<tr>
    <td>Select a File to Load:</td>
    <td><input type="file" id="fileToLoad"></td>
    <td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>

JavaScript

function loadFileAsText(){
  var fileToLoad = document.getElementById("fileToLoad").files[0];

  var fileReader = new FileReader();
  fileReader.onload = function(fileLoadedEvent){
      var textFromFileLoaded = fileLoadedEvent.target.result;
      document.getElementById("inputTextToSave").value = textFromFileLoaded;
  };

  fileReader.readAsText(fileToLoad, "UTF-8");
}