javascript read file from disc 1

javascript read file from disc

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.textContent = contents;
}

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);

Here is what the above code is Doing:
1. When the user clicks the “Choose File” button, the file chooser pops up.
2. When the user selects a file, the onchange event triggers, and the readSingleFile function is executed.
3. The readSingleFile function is passed a reference to the file.
4. The readSingleFile function reads the file and displays its contents in the textarea.

Similar Posts