icelated icelated - 7 months ago 17
HTML Question

Javascript FileReader working in jfiddle, but not in my browser

I have a file reader that works on jfiddle but wont work in any browser. Im using all the latest browsers,. It will let me select the file, but nothing happens afterwards. Im very new to javascript.

javacript

<script type="text/javascript">
function readFile(file) {
var reader = new FileReader();
reader.onload = readSuccess;

function readSuccess(evt) {
var field = document.getElementById('main');
field.innerHTML = evt.target.result;
};
reader.readAsText(file);
}

document.getElementById('selectedFile').onchange = function(e) {
readFile(e.srcElement.files[0]);
};
</script>


html

<input type="file" id="selectedFile" />
<div id="main"></div>


jfiddle

http://jsfiddle.net/fstreamz/ngXBV/1/

Answer

Use window.onload or window.addEventListener("load")

<script type="text/javascript">
  window.onload = function() {
  function readFile(file) {
    var reader = new FileReader();
    reader.onload = readSuccess;

    function readSuccess(evt) {
      var field = document.getElementById("main");
      field.innerHTML = evt.target.result;
    };
    reader.readAsText(file);
  }

  document.getElementById("selectedFile").onchange = function(e) {
    readFile(e.srcElement.files[0]);
  };
}
</script>
Here is the html

<input type="file" id="selectedFile" accept="text/plain" />
<div id="main"></div>

Comments